gpt4 book ai didi

python - 在整数中添加浮点值时获取不同的值(PYTHON)

转载 作者:太空宇宙 更新时间:2023-11-03 14:26:30 24 4
gpt4 key购买 nike

我使用循环在整数中添加浮点值,但答案不同。这是我的代码:

import time
test = 0
while True:
test += 0.0001
print(test)
time.sleep(0.3)

当我运行它时,我应该得到:

0.0001
0.0002
0.0003
0.0004
0.0005
.........

但是我得到了:

0.0001
0.0002
0.00030000000000000003
0.0004
0.0005
0.0006000000000000001
0.0007000000000000001
0.0008000000000000001
0.0009000000000000002
0.0010000000000000002
0.0011000000000000003
0.0012000000000000003

为什么会这样以及如何解决这个问题?

最佳答案

您可以使用{:.4f}设置输出精度以保留四位数字。

>>> pi
3.141592653589793
>>> print("{}".format(pi))
3.141592653589793
>>> print("{:.3f}".format(pi))
3.142
>>> print("{:.4f}".format(pi))
3.1416
>>> print("{:.5f}".format(pi))
3.14159

关于python - 在整数中添加浮点值时获取不同的值(PYTHON),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47604989/

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