当我运行以下Python代码时,我使用Python2.7和Python3.4获得了不同的结果,我不知道为什么.
import sys
def main():
total = 0
number = 568
while number:
total += number % 10
print("total = %d" % total)
number /= 10
if __name__ == '__main__':
main()使用Python2.7输出结果:
共计=8
共计= 14
共计= 19
使用Python3.4的输出结果(我删除了一些输出,因为它太长了):
共计=8
共计= 14
共计= 20
共计= 21
共计= 21
共计= 21
.
发布于 2015-11-17 07:36:58
Python2.x实现整数除法,因此568 / 10 = 56。
Python3.x实现真正的除法,所以568 / 10 = 56.8。
将"total = %d"更改为"total = %f"以查看差异。
若要强制整数除法,请使用//而不是/。
要使Python2像Python3一样工作,请将from __future__ import division添加到脚本的顶部。
https://stackoverflow.com/questions/33751373
复制相似问题