二进制/二等分搜索,以确定每年信用卡的最低月付款额

2024-05-15 14:03:04 发布

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

我试图用二分搜索(平分搜索?)来解决一个在线问题我不确定我的代码哪里出错了,我的答案与预期的答案有一点不同,这对我来说太舒服了。我真的很想知道我在哪里偏离了方向,以及对未来的指示。 我得到了年利率和初始余额。我也被期望选择一个足够小的步骤,这样我就可以增加到分。 我的代码是这样的:

startbalance = input('Balance: ')
annualInterestRate = input('annualInterestRate: ')
monthlyInterestRate = annualInterestRate / 12.0
balance = startbalance
step = 0.01
lowbound = balance / 12.0
highbound = (balance * (1 + monthlyInterestRate)**12) / 12.0
monthlyPayment = (lowbound + highbound) / 2.0

while (monthlyPayment - balance) >= step:

    for month in range(0, 12):
        balance -= monthlyPayment
        balance = balance + ((1 + monthlyInterestRate) * balance)

    if balance < 0:
        highbound = monthlyPayment
        balance = startbalance
    elif balance > 0:
        lowbound = monthlyPayment
        balance = startbalance

print 'Lowest Payment: ', round(monthlyPayment, 2)

使用cases中提供的值测试代码,我有以下内容:

^{pr2}$

我想我只是有点不对劲,我真的很感激你能理直气壮。

谢谢!


Tags: 答案代码inputstep方向balance平分试图用
1条回答
网友
1楼 · 发布于 2024-05-15 14:03:04

修好了(谢谢,zok!)公司名称:

startbalance = input('Balance: ')
annualInterestRate = input('annualInterestRate: ')
monthlyInterestRate = annualInterestRate / 12.0
monthlyInterestRate = annualInterestRate / 12.0
startbalance = balance
step = 0.01
lowbound = startbalance / 12.0
highbound = (startbalance * (1 + monthlyInterestRate)**12) / 12.0
monthlyPayment = (lowbound + highbound) / 2.0

while (abs(startbalance)) >= step:
    startbalance = balance
    for month in range(0, 12):
        startbalance -= monthlyPayment
        startbalance = startbalance + ((monthlyInterestRate) * startbalance)

    if startbalance < 0:
        highbound = monthlyPayment
    if startbalance > 0:
        lowbound = monthlyPayment
    monthlyPayment = (lowbound + highbound) / 2.0

print 'Lowest Payment: ', round(monthlyPayment, 2)

在 在

相关问题 更多 >