[英]Have I made a mistake in my For loop in python code? Model accuracy is too high so double checking
[英]What mistake have i made in my code? Its running but not providing the answer that it should for the input i have shown
这是问题:
你已经从麻省理工学院毕业,现在有一份很棒的工作! 您搬到旧金山湾区并决定开始存钱买房子。 由于湾区的房价非常高,您意识到您将不得不储蓄几年才能负担得起房屋的首付款。 在 A 部分,我们将根据以下假设确定您需要多长时间才能存够足够的钱来付款:
将您梦想中的家的成本称为“i”。
将您迄今为止保存的金额称为“当前”。 您从当前节省的 0 美元开始。
假设您明智地投资您当前的储蓄,年度回报为 r(换句话说,在每个月末,您会收到额外的“当前*r/12”资金用于存入您的储蓄——12 是因为 r是年费率)。 假设您的投资获得 r = 0.04 (4%) 的回报。
假设你的年薪是 i。
假设您打算每个月将一定数量的薪水用于储蓄以支付首付。 称之为'p'。 此变量应为十进制形式(即 0.1 表示 10%)。
在每个月底,您的储蓄将根据您的投资回报,加上您月薪的百分比(年薪 / 12)而增加。 编写一个程序来计算你需要多少个月才能存够足够的钱来支付首付。 你会希望你的主要变量是浮点数,所以你应该将用户输入转换为浮点数。
您的程序应该要求用户输入以下变量:
起薪年薪 (i)
要储蓄的工资部分(p)
你梦想家园的成本 (c)
这是我的代码:
i=int(input("Enter your annual salary:"))
p=float(input("Enter the percent of your salary to save, as a decimal:"))
c=float(input("Enter the cost of your dream home:"))
r=0
current=float(i*p*r/12)
for r in range(9999999):
if current<c:
current=current*(0.04)/12
else:
break
print("Number of months ="+ str( int(r)))
以下输入所需的正确输出是:
Enter your annual salary: 120000
Enter the percent of your salary to save, as a decimal: .10
Enter the cost of your dream home: 1000000
Number of months: 1000
但我得到的输出是:
Enter your annual salary:120000
Enter the percent of your salary to save, as a decimal:.10
Enter the cost of your dream home:1000000
Number of months =9999998
谁能告诉我为什么我错了?
PS:: 非常抱歉之前我上传了一个稍微不同的问题; 我现在已经提供了相关的问题。
问题在这里:
current=current*(0.04)/12
在这一行中,您不累积,而只是覆盖当前的值。
尝试在纸上写出您的解决方案,并问问自己是否有意义。
for r in range(9999999):
if current<c:
current=current*(0.04)/12
else:
break
print("Number of months ="+ str( int(r)))
我注意到的是,无论发生什么, current
都将始终为 0,因为如果current
没有变化,则0 < 1000000
将始终为真。
current=current*(0.04)/12
本质上是0=0*(0.04)/12
,看看它怎么总是0?
当r
遍历范围内的所有 "9999999" 时, r
将在此之前停止,中断并返回给您您注意到Number of months =9999998
。
代码本身运行正常,但我会重新检查逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.