Python 总是向下舍入?

标签 python while-loop rounding-error rounding

<分区>

我正在尝试完成一项作业并且非常接近 python 总是将我的答案四舍五入而不是在应该的时候四舍五入。 这是我的代码:

startingValue = int(input())
RATE = float(input()) /100
TARGET = int(input())
currentValue = startingValue
years = 1

print("Year 0:",'$%s'%(str(int(startingValue)).strip() ))

while years <= TARGET :
  interest = currentValue * RATE
  currentValue += interest
  print ("Year %s:"%(str(years)),'$%s'%(str(int(currentValue)).strip()))
  years += 1

这是我的代码输出: 第 0 年:10000 美元, 第一年:10500 美元, 第二年:11025 美元, 第 3 年:11576 美元, 第 4 年:12155 美元, 第 5 年:12762 美元第 6 年:13400 美元, 7 年级:14071 美元, 第 8 年:14774 美元第 9 年:15513 美元

这是应该输出的内容: 第 0 年:10000 美元, 第一年:10500 美元, 第二年:11025 美元, 第 3 年:11576 美元, 第 4 年:12155 美元, 第 5 年:12763 美元第 6 年:13401 美元, 7 年级:14071 美元, 第 8 年:14775 美元第 9 年:15514 美元

我需要它们匹配,也就是四舍五入。有人请帮助我:(

最佳答案

在 Python 中,int() 构造函数将始终向下舍入,例如

>>> int(1.7)
1

https://docs.python.org/2/library/functions.html#int

If x is floating point, the conversion truncates towards zero.

如果你想总是四舍五入,你需要:

>>> import math
>>> int(math.ceil(1.7))
2

或四舍五入到最接近的:

>>> int(round(1.7))
2
>>> int(round(1.3))
1

(参见 https://docs.python.org/2/library/functions.html#round ...此内置函数返回一个 float )

关于Python 总是向下舍入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52954170/

相关文章:

python - 如何使用 Python 创建简单的网站?

python - 在哪个阶段轮回?

Python小数

python - 用列表中的值替换字符串中的变量名并避免冗余替换

python - 使用 Scrapy 登录 Facebook 时出现问题

java - 重复使用while循环的问题

php - 在while循环中从不同的表中获取数据

for-loop - 尽管我们已经有了 "for loop"或反之亦然,为什么还要创建 "while loop"?

python - 使用 Numpy 在 Python 中使用 float 舍入错误

C++ 四舍五入到 FE_TONEAREST