问题描述
#Code
'''
annual_salary = float(input('What is your starting annual salary?'))
monthly_salary = annual_salary/12
portion_saved = float(input('What percentage of your salary will you save each month(in decimals)?'))
Total_cost = float(input('How much is your dream home?'))
semi_annual_raise = float(input('What is your raise every 6 months(in decimals)?'))
portion_down_payment = 0.25*Total_cost
r = 0.04
current_savings = 0
months = 0
while current_savings < portion_down_payment:
months += 1
if months % 6 == 0:
monthly_salary += semi_annual_raise*monthly_salary
current_savings += portion_saved*monthly_salary + current_savings*r/12
print('Number of months:',months)
#测试 '''
1:Enter your starting annual salary: 120000
Enter the percent of your salary to save,as a decimal: .05
Enter the cost of your dream home: 500000
Enter the semiannual raise,as a decimal: .03
Number of months: 142
2:Enter your starting annual salary: 80000
Enter the percent of your salary to save,as a decimal: .1
Enter the cost of your dream home: 800000
Enter the semiannual raise,as a decimal: .03
Number of months: 159
3:Enter your starting annual salary: 75000
Enter the percent of your salary to save,as a decimal: .05
Enter the cost of your dream home: 1500000
Enter the semiannual raise,as a decimal: .05
Number of months: 261
这是3个测试,请帮助 最后2个分别给我的代码结果158和260 它是一种算法,可以根据工资,半年工资,每月储蓄额和投资回报率来计算节省房屋首付所需的月数。
解决方法
#Code
annual_salary = float(input('What is your starting annual salary?'))
monthly_salary = annual_salary/12
portion_saved = float(input('What percentage of your salary will you save each month(in decimals)?'))
Total_cost = float(input('How much is your dream home?'))
semi_annual_raise = float(input('What is your raise every 6 months(in decimals)?'))
portion_down_payment = 0.25*Total_cost
r = 0.04
current_savings = 0
months = 0
while current_savings < portion_down_payment:
current_savings += portion_saved*monthly_salary + current_savings*r/12
months += 1
if months % 6 == 0:
monthly_salary += semi_annual_raise*monthly_salary
print('Number of months:',months)
#months = 1的错位导致了错误