因此,分配是询问用户在列表中需要多少随机生成的数字,然后从该列表中找到:总(总和),平均值,最小值和最大值。 SOFAR,我在第14行收到错误“类型'int'的对象没有len()”。使用<时,我得到相同的响应太。
import random
def main():
randomList = 0
smallest = 0
largest = 0
average = int(input("How may numbers (between 1-100) would you like to generate?: "))
total = 0
if average >= 101 or average <= 0:
print("Invalid input:How may numbers (between 1-100) would you like to generate?: ")
else:
while randomList != len(int(average)):
randomList.append(random.randint(1,101))
randomList=sorted(randomList)
print(randomList)
total = sum(randomList)
average = float(sum(randomList)) / max(len(randomList))
largest = randomList.pop(average)
smallest = randomList.pop(0)
print('The total of all the numbers are ',str(total))
print('The average of all the numbers are ',str(average))
print('The largest of all the numbers are ',str(largest))
print('The smallest of all the numbers are ',str(smallest))
main()
答案 0 :(得分:0)
以下是您的代码的工作版本。
import random
def main():
smallest = 0
largest = 0
n = int(input("How may numbers (between 1-100) would you like to generate?: "))
total = 0
if n >= 101 or n <= 0:
print("Invalid input:How may numbers (between 1-100) would you like to generate?: ")
else:
randomList = random.choices(range(1, 101), k=n)
print(randomList)
total = sum(randomList)
average = sum(randomList) / len(randomList)
largest = max(randomList)
smallest = min(randomList)
print('The total of all the numbers are ',str(total))
print('The average of all the numbers are ',str(average))
print('The largest of all the numbers are ',str(largest))
print('The smallest of all the numbers are ',str(smallest))
main()
<强>解释强>
许多错误已得到修复:
random.choices
获取指定长度值的随机列表。average
值的上下文中使用average
。确保正确命名和使用变量。average
,largest
,smallest
的计算。此外,我建议您养成通过return
语句返回值的习惯,并将格式设置作为与计算功能分开的步骤。
答案 1 :(得分:-2)
怎么样: randomList = [random.integer()for i in range(userinput)]