【问题标题】:Expensive Calculation Program Operand Confusion昂贵的计算程序操作数混乱
【发布时间】:2021-03-05 12:58:28
【问题描述】:

我要做的是让初始输入接受一个数字,然后继续接受之后输入的数字,直到通过输入 0 关闭循环。输出应该是初始输入,输入的数量加起来,然后从初始数字中减去。

我想尽可能少地改变程序的整体结构。

budget = float(input('Enter amount budgeted for the month: '))
spent = 0
total = 0
while spent >= 0:
    spent = float(input('Enter an amount spent(0 to quit): '))
    total += spent
    print ('Budgeted: $', format(budget, '.2f'))
    print ('Spent: $', format(total, '.2f'))
    if budget > total:
        difference = budget - total
        print ('You are $', format(difference, '.2f'), \
            'under budget. WELL DONE!')
    elif budget < total:
        difference = total - budget
        print ('You are $', format(difference, '.2f'), \
           'over budget. PLAN BETTER NEXT TIME!')
    elif budget == total:
        print ('Spending matches budget. GOOD PLANNING!')

【问题讨论】:

  • 你在循环中忘记了total += spent
  • 另外,你想循环 while spent != 0 - 这意味着你需要将 spent 初始化为 0 以外的东西。
  • @JohnnyMopp 我确实有“总 += 花费”,我的错误是我复制了错误的窗口。我试图将初始值从 0 更改为它只是将其全部破坏。感谢您指出缺少的部分!
  • 您的编辑发生了很大变化...我会输入答案。

标签: python while-loop calculator operands


【解决方案1】:

首先,您需要循环直到用户输入0。您可以使用在0 上中断的循环:

while True:
    spent = float(input('Enter an amount spent(0 to quit): '))
    if spent == 0: break
    total += spent

或循环直到spent 为0。这意味着将其初始化为某个非零值。

spent = -1
while spent != 0:
    spent = float(input('Enter an amount spent(0 to quit): '))
    total += spent

另外,所有其他代码都应该在循环之外:

budget = float(input('Enter amount budgeted for the month: '))
spent = -1
total = 0
while spent != 0:
    spent = float(input('Enter an amount spent(0 to quit): '))
    total += spent
print ('Budgeted: $', format(budget, '.2f'))
print ('Spent: $', format(total, '.2f'))
if budget > total:
    difference = budget - total
    print ('You are $', format(difference, '.2f'), \
                'under budget. WELL DONE!')
elif budget < total:
    difference = total - budget
    print ('You are $', format(difference, '.2f'), \
               'over budget. PLAN BETTER NEXT TIME!')
else:
    print ('Spending matches budget. GOOD PLANNING!')

【讨论】:

  • 谢谢谢谢谢谢!你是个神经保护者!我还在学习很多东西,你的多种方式的回答真的帮助我理解了可能性!我希望你有一个很棒的一天!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-04-09
  • 2020-06-24
  • 1970-01-01
  • 2010-12-15
  • 2013-06-16
  • 2011-03-21
  • 1970-01-01
相关资源
最近更新 更多