简体   繁体   中英

Order of Operation Mathematical

new to programming and came across this while doing a worksheet:

x = 1 / 2 + 3 // 3 + 4 ** 2

what is x ?

I read that in regards to the exponent you have to read it right to left, and I did that and I keep getting 0 for some reason even though the answer was supposed to be 17.5. Any help on why/how I am supposed to get 17.5 and the order I was supposed to work it out from would be greatly appreciated. thanks.

Using Python, the result is 17.5

在此处输入图片说明

You can check the order of the mathematical operators in python (Python Operator Precedence) for more information

(1 / 2) + (3 // 3) + (4 ** 2) = 0.5 + 1 + 16

Ref: https://www.mathcs.emory.edu/~valerie/courses/fall10/155/resources/op_precedence.html

To determine the order of precedence for this expression, keep in mind these rules (non-exhaustive):

  • evaluation goes from left to right
  • Multiplication/division has higher precedence than addition/subtraction (eg 1 + 2 / 3 gets evaluated as 1 + (2 / 3) )
  • Exponent/power has higher precedence than multiplication and division (eg 1 / 2**4 gets evaluated as 1 / (2**4) )

These rules together show us that this expression:

x = 1 / 2 + 3 // 3 + 4 ** 2

Will be evaluated as:

x = (1 / 2) + (3 // 3) + (4 ** 2)

Therefore, x = 0.5 + 1 + 16 = 17.5.

The operator precedence is defined in the Python documentation:

https://docs.python.org/3/reference/expressions.html#operator-precedence

So, ** has the highest precedence, then / and // and then + .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM