Mol*_*lyV 3 python rounding-error rounding while-loop
我正在尝试完成一项作业,并且非常接近 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
Run Code Online (Sandbox Code Playgroud)
这是我的代码输出:第0年:$10000,第1年:$10500,第2年:$11025,第3年:$11576,第4年:$12155,第5年:$ 12762, 第6年:$13400,第7年:$14071, 第8年: $14774, 9年级:$15513,
以下是应该输出的内容: Year 0: $10000, Year 1: $10500, Year 2: $11025, Year 3: $11576, Year 4: $12155, Year 5: $12763 , Year 6 : $13401 , Year 7: $14071, Year 8 :14775 美元, 9 年:15514 美元,
我需要它们匹配,又名四舍五入。有人请帮助我:(
在Python中,int()构造函数总是向下舍入,例如
>>> int(1.7)
1
Run Code Online (Sandbox Code Playgroud)
https://docs.python.org/2/library/functions.html#int
如果 x 是浮点,则转换将截断为零。
如果您想始终向上舍入,您需要:
>>> import math
>>> int(math.ceil(1.7))
2
Run Code Online (Sandbox Code Playgroud)
或四舍五入到最接近的:
>>> int(round(1.7))
2
>>> int(round(1.3))
1
Run Code Online (Sandbox Code Playgroud)
(参见https://docs.python.org/2/library/functions.html#round ...这个内置函数返回一个浮点数)