python - python for循环增量值不是同一个输入
问题描述
start = 0.65
end = 0.75
step = 0.01
while start <= end:
print (start)
start += step
但是为什么我会低于?真的
0.65
0.66
0.67
0.68
0.6900000000000001
0.7000000000000001
0.7100000000000001
0.7200000000000001
0.7300000000000001
0.7400000000000001
0.0000000000000001 是从哪里来的?
多谢!
解决方案
这个问题在此之前已经得到解答。总之,它与值的存储方式有关,因此 0.1 实际上存储为 0.1000000000000000055511151231257827021181583404541015625 因此为什么最后会得到额外的 1。您可以点击链接查看更多内容。要解决这个问题,可以使用内置的round函数。像这样:
start = 0.65
end = 0.75
step = 0.01
while start <= end:
print (start)
start = round(start + step, 2) # this rounds the answer to the nearest hundredth
希望这有帮助!
推荐阅读
- jms - Gatling:模拟期间没有发送请求,不会生成报告
- android - 在Android中使用库时重复类
- android - Android MediaRecorder - 循环录制
- c# - ASP.Net 中的外观不一致
- python-3.x - 由于第 6 行,代码无法运行,它运行但未按设计运行
- python - 将文本从第一人称转换为第二人称时出现忽略引号内文本的问题
- python - 如何在不使用全局变量的情况下重构我的工作?
- android - 重复通知 - react-native-push-notification
- swiftui - macOS 应用程序的 SwiftUI:关闭窗口并打开另一个窗口时的用户 @EnvironmentObject
- python - 使用python在熊猫中根据时间获取不同的值