MIT ps1c.py代码没有乘法正确性

2024-06-30 08:11:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码中有一个乘法错误(乘积比预期的要大得多)。 我已经搜索过类似的代码,它们与我的代码非常相似

我的意见如下:

portionDownPayment = 0.25
currentSavings = 0.0
r = 0.04
months = 36

semiAnnualRaise = 0.07
totalCost = 1000000

annualSalary = float(input("Enter your annual salary: "))

toPay = annualSalary * portionDownPayment

epsilon = 100

floor = 0
top = 100000



while True:
    portionSaved = (floor + top) / 2.0
    print("PortionSaved:", portionSaved / 100000.000)
    currentSavings = 0
    for x in range(1, 37):
        currentSavings += ((annualSalary/1200000) * (portionSaved)) + (currentSavings*r/12)
        months += 1
        if months % 6 == 0:
            annualSalary = (annualSalary) + annualSalary * semiAnnualRaise

    print("Current Savings:", currentSavings)
    print("To pat:", toPay)
    print()

    if abs(currentSavings - toPay) <= epsilon:
        print("Perfect savings rate:", portionSaved / 10000)
        break

    if currentSavings < toPay:
        floor = portionSaved
    elif currentSavings > toPay:
        top = portionSaved

    if top == floor:
        print("Imposible to calculate savings rate with this parameters")
        break

在console中,提示(仅是我发现问题的摘录)如下所示:

PortionSaved: 0.00390625
Current Savings: 75913.48485232962
To pat: 75000.0

PortionSaved: 0.001953125
Current Savings: 56962.83541626017
To pat: 75000.0

PortionSaved: 0.0029296875
Current Savings: 128228.7840548412
To pat: 75000.0

如您所见,当乘以0.0029296875时,当前的节省比乘以0.00390625时大得多

另外,这是我的第一篇帖子,欢迎对帖子提出任何建议


Tags: to代码iftopcurrentprintpatmonths