不知道为什么我运行的结果跟预期输出不一样,哪里出问题了?
问题
total_cost = float(input()) # total_cost为当前房价
annual_salary = float(input()) # 年薪
portion_saved = float(input()) / 100 # 月存款比例,输入30转为30%
semi_annual_rise = float(input()) /100 # 输入每半年加薪比例,输入7转化为7%
portion_down_payment = 0.3 # 首付比例,浮点数
down_payment = portion_down_payment * total_cost # 首付款
print('首付',down_payment)
month_salary=annual_salary/12
current_saving = 0 # 存款金额,从0开始
number_of_months = 0
rate=0.0225/12
month=0
while current_saving<down_payment:
month+=1
current_saving=current_saving*(1+rate)+month_salary*portion_saved
if month%6==0:
month_salary=month_salary*(1+semi_annual_rise)
if month%12==0:
print("第{}个月月末有{:,.0f}元存款".format(month, current_saving))
print("需要{}个月可以存够首付".format(month))

预期与实际输出
total_cost = float(input()) # total_cost为当前房价
annual_salary = float(input()) # 年薪
portion_saved = float(input()) / 100 # 月存款比例,输入30转为30%
semi_annual_rise = float(input()) / 100 # 输入每半年加薪比例,输入7转化为7%
portion_down_payment = 0.3 # 首付比例,浮点数
down_payment = portion_down_payment * total_cost # 首付款
print('首付', down_payment)
month_salary = annual_salary / 12
current_saving = 0 # 存款金额,从0开始
number_of_months = 0
rate = 0.0225 / 12
month = 0
while current_saving < down_payment:
month += 1
#current_saving = current_saving * (1 + rate) + month_salary * portion_saved
if month % 6 == 0:
month_salary = month_salary * (1 + semi_annual_rise)
current_saving = current_saving * (1 + rate) + month_salary * portion_saved #计算加薪后的工资要放在这里
if month % 12 == 0:
print("第{}个月月末有{:,.0f}元存款".format(month, current_saving))
print("需要{}个月可以存够首付".format(month))
问题出现在第六个月的时候涨薪了,计算这个月的工资应该按照涨薪后的算,更改后的代码:
total_cost = float(input()) # total_cost为当前房价
annual_salary = float(input()) # 年薪
portion_saved = float(input()) / 100 # 月存款比例,输入30转为30%
semi_annual_rise = float(input()) / 100 # 输入每半年加薪比例,输入7转化为7%
portion_down_payment = 0.3 # 首付比例,浮点数
down_payment = portion_down_payment * total_cost # 首付款
print('首付', down_payment)
month_salary = annual_salary / 12
current_saving = 0 # 存款金额,从0开始
rate = 0.0225 / 12
month = 0
while current_saving < down_payment:
month += 1
if month % 6 == 0:
month_salary = month_salary * (1 + semi_annual_rise)
current_saving = current_saving * (1 + rate) + month_salary * portion_saved
if month % 12 == 0:
print("第{}个月月末有{:,.0f}元存款".format(month, current_saving))
print("需要{}个月可以存够首付".format(month))