请问为什么代码只为前三次迭代提供最小和最大的正确输出?
我前三次迭代的输出正常工作。最小和最大变量被锁存到这些值,并且不会根据新输入进行更新。 剩余的计算(总和,计数和平均值)工作正常。
[enter image description here][1]
count= 0
sum=0
average=0
minimal=None
maximum=None
while True:
number=raw_input("Enter a number: ")
try:
if (number=='done'):
break
else:
count=count+1
sum=sum+float(number)
if minimal==None:
minimal=float(number)
maximum=float(number)
else:
minimal=min(number,minimal)
maximum=max(number,maximum)
print maximum
print minimal
average=sum/count
#print ("Calc done")
except:
print ("Invalid input")
print("Count: %d, Sum=%d and Average=%d" %(count,sum,average))
print("smallest number is %d" %minimal)
print("largest number is %0.2f" %float(maximum))
答案 0 :(得分:1)
在您的函数调用min(number,minimal)
和max(number,maximum)
中,您不会将number
强制转换为浮点数。这必须以minimal
完成,maximum
是浮点类型。
尝试将参数number
替换为float(number)
,如下所示:
minimal=min(float(number),minimal)
maximum=max(float(number),maximum)
答案 1 :(得分:0)
下面的代码有效。请看差异:
count= 0
sum=0
average=0
minimal=None
maximum=None
while True:
number=raw_input("Enter a number: ")
try:
if (number=='done'):
break
else:
count=count+1
sum=sum+float(number)
if minimal==None:
minimal=float(number)
maximum=float(number)
else:
minimal=min(float(number),minimal)
maximum=max(float(number),maximum)
print maximum
print minimal
average=sum/count
#print ("Calc done")
except:
print ("Invalid input")
print("Count: %d, Sum=%d and Average=%d" %(count,sum,average))
print("smallest number is %d" %minimal)
print("largest number is %0.2f" %float(maximum))