计算表达式 `3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6`

0 投票
2 回答
6540 浏览
提问于 2025-04-18 14:30

考虑这个表达式 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6

DuckDuckGo 计算这个表达式的结果是 6.75(谷歌也是这样算的)。

在 Python 2 中,这个表达式的结果是 7:

$ python
Python 2.7.5 (default, Mar  9 2014, 22:15:05) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
7
>>> ^D

而在 Python 3 中,结果是 6.75:

$ python3
Python 3.4.0 (default, Apr  9 2014, 11:51:10) 
[GCC 4.2.1 Compatible Apple LLVM 5.1 (clang-503.0.38)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6)
6.75
>>>`enter code here`

为什么 Python 2 的结果是 7,而 Python 3 的结果是 6.75 呢?

Python 是怎么得出这个结果的呢?

2 个回答

0

在Python 2.x中,整数相除会去掉小数部分。

Python并没有忘记怎么做数学运算,有时候你只需要给它更多的指令。如果你对这个表达式做一个简单的修改:

print 3 + 2 + 1 - 5 + 4 % 2 - 1.00 / 4 + 6

你应该能得到6.75这个结果。

3

在Python 2中,1除以4的结果是0,因为它只考虑整数的部分。而在Python 3中,1除以4的结果是0.25,因为它会给出更精确的小数结果。你可以在Python 2中使用明确的真除法来得到小数结果。

3 + 2 + 1 - 5 + 4 % 2 - 1. / 4 + 6  # note the decimal point

或者你可以做一个

from __future__ import division

来使用Python 3的行为。

撰写回答