微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

昂贵的计算程序操作数混乱

如何解决昂贵的计算程序操作数混乱

我想要做的是让初始输入取一个数字,然后继续取之后输入的数字,直到通过输入 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 $',\
           'over budget. PLAN BETTER NEXT TIME!')
    elif budget == total:
        print ('Spending matches budget. GOOD PLANNING!')

解决方法

首先,您需要循环直到用户输入 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 $',\
               'over budget. PLAN BETTER NEXT TIME!')
else:
    print ('Spending matches budget. GOOD PLANNING!')

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。