我正在写一个程序,它应该将用户输入的所有正值相加,程序应该循环,直到他/她输入一个负数。程序循环很平稳,但它的和中包含了负数。感谢您的帮助
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()
在输入数字之前进行加法
X = X + Y
(但在while
内)。您初始化了这两个变量,因此在输入数字之前的“额外”加法只是X = 0 + 0
,没有负面影响否则,它将在while循环退出之前再执行一次加法(即使您输入了负数)。while循环的条件只有在第一次尝试进入时才被测试,每次它内部的代码完成时,程序检查是否应该执行另一个“循环”
相关问题 更多 >
编程相关推荐