Python总是四舍五入吗?

时间:2018-10-23 16:52:08

标签: 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, 1年:$ 10500, 2年:$ 11025, 3年:$ 11576, 4年:$ 12155, 五年级:$ 12762 六年级:$ 13400 , 7年:$ 14071, 8年级:$ 14774 9年级:$ 15513

这是应该输出的内容: 0年:$ 10000, 1年:$ 10500, 2年:$ 11025, 3年:$ 11576, 4年:$ 12155, 五年级:$ 12763 六年级:$ 13401 , 7年:$ 14071, 8年级:14775美元 9年级:$ 15514

我需要他们来配合,又叫四舍五入。有人请帮我:(

2 个答案:

答案 0 :(得分:0)

投射到int时总是截断;想象一下它会砍掉所有小数点。

使用round()舍入到最接近的整数。

答案 1 :(得分:0)

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

>>> int(1.7)
1

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

  

如果x为浮点数,则转换将截断为零。

如果要始终取整,则需要:

>>> 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 ...此内置函数返回浮点数)