求值+2+4%1表达式`

2024-03-29 10:41:03 发布

您现在位置:Python中文网/ 问答频道 /正文

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

DuckDuckGo将其计算为6.75(Google也是如此)。在

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

Python3将其计算为6.75:

^{pr2}$

为什么python2的计算结果是7,python3的计算结果是6.75?在

Python是如何得到结果的?在


Tags: defaultapple表达式ontypegooglehelpmar
2条回答

python2.x中的整数除法会截断。在

Python并没有忘记如何做数学,您只需要有时给它更多的指令。如果你改变一个简单的表达式

打印3+2+1-5+4%2-1.00/4+6

你应该拿到你的6.75英镑

在py2中,1/4->;0表示整数;在py3中,1/4->;0.25。可以在py2中使用显式的真除法

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

或者你可以做一个

^{pr2}$

使用py3行为。在

相关问题 更多 >