代码运行正常,尽管我需要将其减少到只有两位小数,例如 38374.96 而不是 38374.967777777
#!/usr/bin/python3
amount = float(input("Enter a starting value: "))
result = {}
# looping for 10 times
for i in range(1,11):
# updating amount
amount = amount * 1.01
# updating result
result[str(i) + " years"] = amount
# printing result
print(result)
答案1
如果您不需要支持低于 3.6 的 python 版本,您通常应该更喜欢更新的插值 F 字符串:
>>> x = 1.312345345673845723
>>> f"{x:.2f}"
'1.31'
答案2
你可以使用这个:
...
result[str(i) + " years"] = "{:.2f}".format(amount)
...
结果:
Enter a starting value: 10
{'1 years': '10.10', '2 years': '10.20', '3 years': '10.30', '4 years': '10.41', '5 years': '10.51', '6 years': '10.62', '7 years': '10.72', '8 years': '10.83', '9 years': '10.94', '10 years': '11.05'}