简体   繁体   English

数学运算顺序

[英]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 ? 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.我读到了关于指数的内容,你必须从右到左阅读,我这样做了,尽管答案应该是 17.5,但由于某种原因我一直得到 0。 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.任何关于为什么/如何我应该得到 17.5 以及我应该解决它的顺序的帮助将不胜感激。 thanks.谢谢。

Using Python, the result is 17.5使用Python,结果是17.5

在此处输入图片说明

You can check the order of the mathematical operators in python (Python Operator Precedence) for more information您可以在 python (Python Operator Precedence) 中检查数学运算符的顺序以获取更多信息

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

Ref: https://www.mathcs.emory.edu/~valerie/courses/fall10/155/resources/op_precedence.html参考: 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) )乘法/除法比加法/减法具有更高的优先级(例如1 + 2 / 3被评估为1 + (2 / 3)
  • Exponent/power has higher precedence than multiplication and division (eg 1 / 2**4 gets evaluated as 1 / (2**4) )指数/幂比乘法和除法具有更高的优先级(例如1 / 2**4被评估为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.因此,x = 0.5 + 1 + 16 = 17.5。

The operator precedence is defined in the Python documentation:运算符优先级在 Python 文档中定义:

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

So, ** has the highest precedence, then / and // and then + .因此, **具有最高优先级,然后是/// ,然后是+

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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