gpt4 book ai didi

Python 数学运算顺序

转载 作者:行者123 更新时间:2023-11-28 19:53:09 24 4
gpt4 key购买 nike

请有人向我解释为什么表达式 2 + 4/2 * 3 的计算结果为 8.0 而不是 2.66?

我以为乘法是在除法之前执行的,但是在这个例子中,除法运算似乎是在乘法之前执行的。

最佳答案

因为它被评估为:

2 + ((4 / 2) * 3)

因为*/higher precedence + 并且当运算符具有相同的优先级时,它从左到右。

引用自文档:

The following table summarizes the operator precedence in Python, from lowest precedence (least binding) to highest precedence (most binding). Operators in the same box have the same precedence. Unless the syntax is explicitly given, operators are binary. Operators in the same box group left to right (except for exponentiation, which groups from right to left).

Operator Description

  • [...]
  • +, - Addition and subtraction
  • *, @, /, //, % Multiplication, matrix multiplication, division, floor division, remainder
  • [...]

关于Python 数学运算顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46379901/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com