【问题标题】:Python: for loop with counter and scheduled increase in increasePython:带有计数器的for循环和计划增加的增加
【发布时间】:2021-07-19 04:16:23
【问题描述】:

Python 学习者。处理每月定期存款,利息问题。除了在这个假设中,我被要求每 6 个月加薪一次。我在比预期更少的几个月内达到了目标数量。

目前正在使用 % 函数和 += 函数

annual_salary = float(input("What is your expected Income? "))                  
portion_saved = float(input("What percentage of your income you expect to save? "))
total_cost = float(input("what is the cost of your dream home? "))
semi_annual_raise = float(input("Enter your expected raise, as a decimal "))

monthly_salary = float(annual_salary/12)
monthly_savings = monthly_salary * portion_saved
down_payment= total_cost*.25
           
savings = 0
for i in range(300):
    savings = monthly_savings*(((1+.04/12)**i) - 1)/(.04/12)
    if float(savings) >= down_payment:
            break
    if i % 6 == 0 :
        monthly_salary += monthly_salary * .03
        monthly_savings = monthly_salary * portion_saved

【问题讨论】:

  • 您的预期结果是什么。还有什么'n'
  • monthly_savings 值是多少,r 是多少,您预计需要多少个月?
  • 在 115 个月而不是 142 个月内达到了储蓄目标。在原始帖子中添加了上下文。谢谢。
  • 你应该考虑在第一个月加薪吗?当 'i' 为 0 时,monthly_salary 将被更新。 Range(1, 301) 会解决这个问题。

标签: python loops counter


【解决方案1】:

感谢大家的建议。我的代码越来越清晰,我得到了正确的输出!问题在于我计算利息的方式和时间。在静态贡献的情况下,我成功地使用了定期存款利息的公式,在这里,需要更简单的每月计算利息的移动来处理循环流程。

annual_salary = float(input("What is your expected Income? "))                  
portion_saved = float(input("What percentage of your income you expect to save? "))
total_cost = float(input("what is the cost of your dream home? "))
semi_annual_raise = float(input("Enter your expected raise, as a decimal "))
monthly_salary = float(annual_salary/12)
monthly_savings = monthly_salary * portion_saved
down_payment = total_cost*.25

savings = 0
month = 1
while savings < down_payment :
    print(savings)
    savings += monthly_savings
    savings = savings * (1+(.04/12))
    month += 1  

    if month % 6 == 0 :
            monthly_salary += (monthly_salary * semi_annual_raise)
            monthly_savings = (monthly_salary * portion_saved)

print("")
print("it will take " + str(month) + " months to meet your savings goal.")

【讨论】:

    【解决方案2】:

    这样的事情对你有用吗?通常,当我们不知道循环最终需要多少次迭代时,我们希望使用while 循环而不是for 循环。

    monthly_savings = 1.1 # saving 10% each month
    monthly_salary = 5000
    down_payment = 2500
    interest = .02
    savings = 0
    months = 0
    
    while savings < goal:
        print(savings)
        savings = (monthly_salary * monthly_savings) + (savings * interest)
        months += 1
        
        if months % 6 == 0 :
            monthly_salary += monthly_salary * .03
            
    print("Took " + str(months) + " to save enough")
    

    【讨论】:

      猜你喜欢
      • 2012-11-26
      • 2023-03-08
      • 2013-12-16
      • 1970-01-01
      • 1970-01-01
      • 2018-06-11
      • 2011-06-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多