Python是否总是向下取整?

3

我正在尝试完成一个任务,但是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
我需要它们匹配,即四舍五入。请有人帮帮我:(

1
Python的int默认向下取整。看起来你需要四舍五入到最近的整数:https://dev59.com/A1wZ5IYBdhLWcg3wINTQ - milancurcic
你需要将其四舍五入或者向最接近的整数取整吗? - Siong Thye Goh
要始终向上舍入,请使用 math.ceil - John Coleman
如果你在谷歌上搜索“Python rounding”这个短语,你会发现有很多教程可以比我们在这里回答更好地解释它。 - Prune
我需要它们四舍五入到最接近的数值。 - MollyV
2个回答

5

0

将数据类型转换为 int 时,总是会进行截断;可以想象它会将所有小数点都砍掉。

使用 round() 函数可以将数据四舍五入到最近的整数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接