首页 > 解决方案 > Python总是四舍五入?

问题描述

我正在尝试完成一项作业,并且非常接近 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, 第 5 年:$12762第 6 年:$13400,第 7 年:$14071, 第 8 年: 14774 美元第 9 年:15513 美元

以下是应该输出的内容: 第 0 年:$10000,第 1 年:$10500,第 2 年:$11025,第 3 年:$11576,第 4 年:$12155, 第 5 年:$12763第 6 年:$13401,第 7 年:$14071, 第 8 年: $14775 , 第 9 年: $15514 ,

我需要他们匹配,AKA 围捕。有人请帮助我:(

标签: pythonwhile-looprounding-errorrounding

解决方案


在 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 ...这个内置函数返回一个浮点数)


推荐阅读