所以我正在尝试编写一个程序,它接受正数和负数,然后在输入0后在末尾显示它们,
pos1=0
neg1=0
all1=0
flt1=float(raw_input("enter a non-zero floating point number (decimals): "))
while(flt1!=0.0):
if (flt1 < 0.0):
neg1=neg1+flt1
all1=all1+flt1
elif(flt1 > 0.0):
pos1=pos1+flt1
all1+all1+flt1
print "the sum of all numbers entered is ",all1,"the sum of all positive numbers are ",pos1,
print "and the sum of all negitive numbers are ",neg1,
我的问题是,当我实际跟踪它时(如果我使用say 5.0并跟踪它),我会发现它被卡在代码的"elif"部分,实际上不会回来要求另一个数字。我一直在想我需要做什么才能让它回来并要求另一个非零的数字。我的目标是让用户不断输入数字,直到他/她输入0,然后它会把所有的负数加在一起并显示它们,然后对正数也这样做,然后显示到目前为止输入0的全部总和(负数和pos)
编辑:修复elif循环上的缩进
只需将flt1=...
行放入循环中。
此外,您通常应该避免浮动相等比较,尽管零是可以的。
并且应该使用空白(n = 72 + 61 * x
,而不是n=72+61*x
)。
伪代码:
while True:
num = input
if num > 0.0:
do_stuff()
elif num < 0.0:
do_neg_stuff()
else:
break