我正在创建一个程序,我要求用户使用循环(不是函数)输入数字 我需要假设数字是浮动的。 用户将继续输入数字,直到他们第二次按下回车键。 然后程序将生成最大数量,最小数字,列表总和和平均数。
我已经把所有事情都解决了,但是当我输入10或更大的数字时,该程序并没有将其识别为最大的。事实上,我注意到10被认为是最小的数字。
此外,我无法转换浮动数字。
myList = []
done = False
while not done:
enterNumber = raw_input("Enter a number (press Enter key a second time to stop): ")
nNumbers = len(myList)
if enterNumber == "":
done = True
break
else:
myList.append(enterNumber)
print "You've typed in the following numbers: " + str(myList)
smallest = 0
largest = 0
for nextNumber in myList:
if smallest == 0 or nextNumber < smallest:
smallest = nextNumber
for nextNumber in myList:
if largest == 0 or largest < nextNumber:
largest = nextNumber
print "Largest number from this list is: " + largest
print "Smallest number from this list is: " + smallest
sum = 0
for nextValue in myList:
sum = sum + float(nextValue)
print "The sum of all the numbers from this list is: " + str(sum)
average = float(sum/nNumbers)
print "The average of all the numbers from this list is: " + str(average)
答案 0 :(得分:0)
这告诉我你可能没有比较你的想法:)。
你的代码大多是正确的,除了你从未告诉python用户输入的“类型”是什么。我猜python假设用户输入了一串字符串,并且在字符串世界中 - “10”&lt; “9”
因此,在您的代码中,强制“enterNumber”的类型为浮点数,然后将其添加到浮动列表中,如下所示:
while not done:
enterNumber = raw_input("Enter a number (press Enter key a second time to stop): ")
nNumbers = len(myList)
if enterNumber == "":
done = True
break
else:
myList.append(float(enterNumber))
答案 1 :(得分:0)
在将其添加到列表中之前,您需要对其进行转换
enterNumber = raw_input("Enter a number (press Enter key a second time to stop): ")
nNumbers = len(myList)
if enterNumber == "":
done = True
break
else:
myList.append(float(enterNumber)) # convert it here...
#you may want to check for valid input before calling float on it ...
但我最喜欢的获取数字列表的方法是
my_numbers = map(float,
iter(lambda:raw_input("Enter a number or leave blank to quit").strip(),""))