如何对输入中的数字求和? [英] How to sum numbers from input?

查看:77
本文介绍了如何对输入中的数字求和?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在解决以下问题.

编写一个程序,该程序连续提示输入正整数,并在输入的数字总和超过1000时停止. 但是如果输入负整数,我的代码就会提前停止.

Write a program that continually prompts for positive integers and stops when the sum of numbers entered exceeds 1000. But my code stop early if a negative integer is entered.

数字不会相加.

我的代码:

x = int(input("Enter an integer:"))
total = 0
sum = 0
while (0 <= x):
    if sum <= 1000:
        x += 1
        sum += (int(input("Enter an integer:")))
    elif sum >= 1000:
        break

推荐答案

x = 0
total = 0
sum = 0
while sum <= 1000:
    x = int(input("Enter an integer:"))
    if x<0:
        print("Invalid negative value given")
        break
    sum += x


第一:

if sum >= 1000:
    ...
elif sum < 1000:
    ...

是多余的,因为如果您尝试sum >= 1000,并且达到了elif,您就会清楚地知道条件是False,因此sum < 1000必须为真.因此,您可以将其替换为

is redundant, because if you chek for sum >= 1000, and the elif is reached, you aready know, that the condition was False and therefore sum < 1000 has to be true. So you could replace it with

if sum >= 1000:
    ...
else:
    ...


第二:
您要使用x检查输入是否为负.到现在为止,您每次都将它简单地增加一倍.相反,您应该首先将输入关联到x,然后将其添加到sum.这样做是这样的:


Second:
You want to use x to check, whether the input is negative. Until now, you were simpy increasing it by one each time. Instead, you should first assing the input to x, and then add this to sum. So do it like this:

x = int(input("Enter an integer:"))
if x<0:
    break
sum += x

这篇关于如何对输入中的数字求和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆