【发布时间】:2017-05-03 01:09:09
【问题描述】:
编写一个程序来计算您需要多少个月才能存够一笔首付。像以前一样,假设您的投资获得 r = 0.04(或 4%)的回报,并且 所需的首付百分比为 0.25(或 25%)。让用户输入以下变量:
- 起薪年薪(annual_salary)
- 要节省的工资百分比 (portion_saved)
- 梦想家园的成本 (total_cost)
- 半年加薪(semi_annual_raise)em
这应该是正确的结果: 但是我的程序通过了第一次测试,但在其他两个测试中延迟了一个月,我找不到解决方案
测试用例 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
代码:
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)
【问题讨论】:
-
这是一个浮点小数精度问题,尝试在后期使用 int() 或 tuple() 进行转换,许多金融计算器实际上被“修改”为“精确不准确”来纠正为此
-
欢迎来到 StackOverflow。请阅读并遵循帮助文档中的发布指南。 Minimal, complete, verifiable example 适用于此。在您发布 MCVE 代码并准确描述问题之前,我们无法有效地帮助您。具体来说,正确答案是什么,您运行了哪些调试跟踪?我们应该能够将您发布的代码粘贴到文本文件中并重现您描述的问题。
-
我得到了 142、158 和 260 三个运行的结果。我正在使用 Python 3.5.2
-
是的,我得到了相同的结果,但它们假设为 142、159、261。我猜 Oliver 是对的,它是一个浮点小数精度问题
-
尝试使用小数模块进行任意精度计算。
标签: python