Python 计算房屋首期付款所需的储蓄月数
写一个程序来计算你需要多少个月才能攒够一笔定金。与之前一样,假设您的投资获得r=0.04(或4%)的回报,并且 要求的首付款百分比为0.25(或25%)。让用户输入以下变量:Python 计算房屋首期付款所需的储蓄月数,python,Python,写一个程序来计算你需要多少个月才能攒够一笔定金。与之前一样,假设您的投资获得r=0.04(或4%)的回报,并且 要求的首付款百分比为0.25(或25%)。让用户输入以下变量: 起始年薪(年薪) 要保存的工资百分比(保存的部分) 你梦想之家的成本(总成本) 半年度加薪(半年度加薪)em 这应该是正确的结果: 但是我的程序通过了第一次测试,但在另外两次测试中又差了一个月,我找不到解决方案 测试用例1 Enter your starting annual salary: 120000 Enter th
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
代码:
年薪=int(输入(“工资:”)
部分保存=浮动(输入(“保存百分比:”)
总成本=整数(输入(“房屋成本:”)
部分首付=总成本*0.25
当前储蓄=0
比率=0.04
月数=0
半年度上升=浮动(输入(“上升:))
当活期储蓄而活期储蓄<首付:
应该是这样的,这就是为什么你是一次性的这是一个浮动小数精度的问题,在后面的阶段尝试使用int()或tuple()进行转换,许多金融计算器实际上被“修改”为“精确不准确”,以纠正这个欢迎StackOverflow的问题。请阅读并遵循帮助文档中的发布指南。适用于这里。在您发布MCVE代码并准确描述问题之前,我们无法有效地帮助您。具体来说,正确答案是什么,您运行了哪些调试跟踪?我们应该能够将您发布的代码粘贴到文本文件中,并重现您描述的问题。我得到的三次运行结果分别为142、158和260。我使用的是Python3.5.2是的,我得到了相同的结果,但它们假设为142159261。我想oliver是对的,这是一个浮动十进制精度问题。尝试使用十进制模块进行任意精度计算。尝试将其作为注释发送。
annual_salary = int(input("Salary: "))
portion_saved = float(input("Percentage to save: "))
total_cost = int(input("Cost of the house: "))
portion_down_payment = total_cost * 0.25
current_savings = 0
rate = 0.04
number_of_months = 0
semi_annual_raise = float(input("Raise: "))
while current_savings <= portion_down_payment:
current_savings += annual_salary * portion_saved / 12
current_savings += current_savings * rate / 12
number_of_months += 1
if number_of_months % 6 == 0:
annual_salary += annual_salary * semi_annual_raise
print(number_of_months, current_savings)
print("Enter your annual salary: ", annual_salary)
print("Enter the percent of your salary to save, as a decimal: ", portion_saved)
print("Enter the cost of your dream home: ", total_cost)
print("Number of months: ", number_of_months)