Python总是向下舍入吗?
我正在努力完成一项作业,而python总是在我的答案应该是向下舍入而不是向上舍入的时候,非常接近我的答案。 这是我的密码:Python总是向下舍入吗?,python,while-loop,rounding-error,rounding,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
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
startingValue=int(输入())
速率=浮动(输入())/100
TARGET=int(输入())
currentValue=启动值
年=1
打印(“第0年:”、“$%s%”(str(int(startingValue)).strip())
而年铸造到int
总是截断;想象一下,它砍掉了所有的小数点
使用round()
四舍五入到最接近的整数。在Python中int()
构造函数总是向下舍入,例如
>>> int(1.7)
1
如果x是浮点,则转换将向零截断
如果您希望始终汇总,您需要:
>>> import math
>>> int(math.ceil(1.7))
2
或四舍五入至最接近:
>>> int(round(1.7))
2
>>> int(round(1.3))
1
(请参见…此内置项返回浮点)Python的int
默认情况下向下舍入。听起来你需要四舍五入到最接近的整数:你需要四舍五入还是四舍五入到最接近的整数?要始终四舍五入,请使用math.ceil
如果你在谷歌上搜索短语“Python四舍五入”,你会找到比我们在这里的答案更好的教程来解释它。我需要他们四舍五入到最接近的整数