Python 3.x 为什么小数点被忽略了?
所以我正在研究这个小复利计算器,我遇到了一个我不知道如何解决的问题! 出于某种原因,python似乎并不关心数字中有小数这一事实。例如,如果代码中的数字为12588.01,则将其视为12588。 非常感谢您的帮助Python 3.x 为什么小数点被忽略了?,python-3.x,numbers,Python 3.x,Numbers,所以我正在研究这个小复利计算器,我遇到了一个我不知道如何解决的问题! 出于某种原因,python似乎并不关心数字中有小数这一事实。例如,如果代码中的数字为12588.01,则将其视为12588。 非常感谢您的帮助 p = 12588.01 #principle r = 4.9 #rate as percent t = 20 #time # math r = r / 100 # math and output for i in range(t): interest = p * r
p = 12588.01 #principle
r = 4.9 #rate as percent
t = 20 #time
# math
r = r / 100
# math and output
for i in range(t):
interest = p * r
#interest = round(interest, 2)
#generates the spaces between the time and numbers
timeSpace = 5 - len(str(i+1))
timeSpace = " " * int(timeSpace)
#generates the spaces used in the first part of the output
firstSpace = 10 - len(str(round(p)))
firstSpace = " " * int(firstSpace)
#generated the space used in the second part of the output
secondSpace = 10 - len(str(round(interest)))
secondSpace = " " * int(secondSpace)
#output
#print("Year: %d%s|%d%s|%d%s|%d" % (i+1, timeSpace, round(p, 2), firstSpace, interest, secondSpace, round(interest+p, 2)))
print("Year: %d%s|%d%s|%d%s|%d" % (i+1, timeSpace, float(p), firstSpace, float(interest), secondSpace, float(interest+p)))
p = p + interest
#p = round(p, 2)
此计算器使用的是货币,因此应该舍入,但是在我尝试修复代码时,我将其注释掉。您正在使用
%d
打印浮点,这是用于整数的。使用%.2f
打印小数点后两位的浮点。使用正确格式的字符串格式:
p = 12588.01 #principle
r = 4.9 #rate as percent
t = 20 #time
r /= 100
for i in range(t):
interest = p * r
print(f"Year: {i+1:<5d}|{p:<10.2f}|{interest:<10.2f}|{interest+p:.2f}")
p += interest
p=12588.01#原则
r=4.9#以百分比表示的比率
t=20次
r/=100
对于范围(t)内的i:
利息=p*r
打印(f)年份:{i+1: