所以我正在做这个小的复利计算器,我有一个问题,我不知道怎么解决!出于某种原因,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
#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)这个计算器正在使用货币,因此应该循环,但是在我尝试修复代码的过程中,我将它们注释掉了。
发布于 2020-02-11 04:33:18
您使用%d打印浮点数,这是用于整数的。使用%.2f将浮点数打印到小数点后两位。
发布于 2020-02-11 04:51:34
使用具有正确格式的字符串格式:
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 += interesthttps://stackoverflow.com/questions/60157955
复制相似问题