我正在编写一个程序,该程序应该添加用户输入的所有正值,程序应该循环直到他/她输入负数。程序顺利循环,但它包括总和中的负数。任何帮助表示赞赏!
def main ():
X=0
Y=0
print("I can add the sum of all positive numbers")
X = int (input ("Please enter a positve number between 0 and infinity: "))
if X > 0:
while Y >= 0:
print("I can add the sum of all positive numbers")
Y = int(input("Please enter a positive number between 0 and infinity: "))
X = X + Y
print("The sum of the numbers you entered is: ", X)
else:
print("Sorry I can only add positive numbers")
main()
答案 0 :(得分:0)
在输入数字之前添加X = X + Y
(但在while
内)。您初始化了两个变量,因此在输入数字之前添加“额外”只是X = 0 + 0
并且没有负面影响。
否则它将在while循环退出之前再次执行添加(即使您输入了负数)。 while循环的条件仅在首次尝试输入时进行测试,并且每次完成其中的代码并且程序检查是否应该执行另一个“循环”。