官术网_书友最值得收藏!

Arithmetic order of operations

When using arithmetic operators, it's important to understand the order of operations, as the compiler uses a specific format to determine this order.

So, what does this order mean for a problem/equation?

Let's say that we need to run an equation with all these operators, but in a different order. For example: 5 + 15 * 20 - 2 / 6 ** 3 - (3 + 1).

In the preceding problem, we have all the six operations included. If we run this code, it gives a value of 301.

To break it down, the compiler first looked for the parentheses, so it computed the value (3+1), which is 4. Then, it handled the exponent 6**3, which is 216. Next is multiplication, so 15 * 20 is 300. Now, for division, 2/216 will be equal to 0 (it's not really zero, but we'll discuss this in the next section). Next, it focuses on addition, 5 + 300 which equals 305. And lastly subtraction: 305 - 4 which equals 301.

You can see the step-by-step path here:

5 + 15 * 20 - 2 / 6 ** 3 - (3 + 1)  # parenthesis
5 + 15 * 20 - 2 / 6**3 - 4 # exponents
5 + 15 * 20 - 2 / 216 - 4 # multiplication
5 + 300 - 2 / 216 - 4 # division
5 + 300 - 0 - 4 # addition
305 - 0 - 4 # subtraction
301

A good way to remember this order is with the acronym PEMDAS or with the sentence Please Excuse My Dear Aunt Sally.

What this stands for is as follows:

  • P: Parentheses
  • E: Exponent
  • M: Multiplication
  • D: Division
  • A: Addition
  • S: Subtraction

Now, this format is not just for numbers but also for other programming components such as conditionals (which we will cover in a future section). Consider this example, where you have a conditional like the following:

if (x > 7 && y < 19) || z == 5 

The value inside the parentheses will get executed first.

主站蜘蛛池模板: 巩留县| 白朗县| 镇安县| 喀喇沁旗| 蛟河市| 维西| 囊谦县| 尼玛县| 六安市| 嘉黎县| 织金县| 台江县| 新乐市| 屏边| 金华市| 伊宁县| 奉新县| 元朗区| 泸溪县| 土默特左旗| 特克斯县| 玉林市| 宜川县| 咸宁市| 蒙山县| 海淀区| 来安县| 罗源县| 闸北区| 民乐县| 平乐县| 南昌市| 廊坊市| 镇平县| 灵石县| 香格里拉县| 金堂县| 新巴尔虎右旗| 民权县| 九寨沟县| 广宁县|