为什么我的Python的 while循环执行得比需要的还多?
我在下面这段Python代码上遇到一个小问题,该代码本应使用while循环,给出在给定年利率下投资翻倍所需的年数。
initialInvestment = 10
intRate = 2
newBalance = initialInvestment
years = 0
if initialInvestment > 0: # Make sure user has a valid investment balance
while newBalance < (2 * initialInvestment):
newBalance += (newBalance * (intRate/100)) # Update balance
years += 1
print(f'At {years} year(s), you would have ${newBalance:,.2f}')
else:
print(f'Please enter an investment amount greater than zero.')
print(f'It would take {years} years to double your investment of ${initialInvestment:,.2f} at {intRate}%."')
我一直在while循环内使用print语句来跟踪余额和年数,结果发现代码在退出前会多算了一整年。例如,我以10美元作为初始投资,利率为2%。print语句显示在第35年时newBalance为 20美元,恰好是初始投资的两倍,但循环却再执行一次。我甚至把条件改成 while ... and newBalance != (2 * initialInvestment),代码仍未在35年时停止。
诚然,我并不需要跟踪逐年的余额,因此可以把years初始化为 -1,但我更想弄清问题所在以及如何纠正它。
解决方案
你的问题在于你把结果只四舍五入到两位小数:如果改成
print(f'At {years} year(s), you would have ${newBalance:,.10f}')
你将看到
At 35 year(s), you would have $19.9988955266
这还没有完全翻倍。
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。