我正在试图弄清楚为什么这段代码不起作用!唯一没有工作的部分是最小的数字,它总是回到零?我做错了什么?
import random
X = random.randint(10,15)
pickedNumber =int( input("Please enter a number: "))
print("Generating", (pickedNumber), "random Numbers between 20 and 50:")
for numberCount in range(1,pickedNumber+1):
numberCount = random.randint(20,50)
sum = 0
sum += numberCount
print(numberCount)
print('The sum = ',sum)
print('the average = ', sum/pickedNumber)
for pickedNumber in range(0,X,1):
number = random.randint(20,50)
if pickedNumber== 0 or pickedNumber < smallestNumber:
smallestNumber = pickedNumber
print('The smallest = ',smallestNumber)
答案 0 :(得分:0)
您的代码存在一些我不会直接解决的问题,但是对于查找整数列表中的最小项,只需对列表进行排序并返回列表中的第一项:
some_list = [5,7,1,9]
sorted_list = sorted(some_list)
smallest = sorted_list[0]
>>> smallest
1
您不一定需要创建第二个列表来存储排序结果,它只是用于说明差异。
编辑:您也可以将生成的第一个随机int存储为smallestNumber
,然后在创建每个新的随机int时将其与smallestNumber
进行比较,如果新的int较小,则设置{{ 1}}到它。
示例:
smallestNumber
依此类推,//stuff to generate random int done here
smallest = new_random_int
//generate the next random int
if next_random_int < smallest:
smallest = next_random_int
是你生成的第一个随机整数,new_random_int
是你之后生成的任何随机整数。
另外,欢迎来到Stack Overflow!
答案 1 :(得分:0)
谢谢大家,我最终搞清楚这样做了。
import random
largest = 0
sum = 0
pickedNumber =random.randint(10,15)
print("Generating", (pickedNumber), "random Numbers between 20 and 50:")
number = random.randint(20,50)
sum += number
print(number)
largest = number
smallest = number
for numberCount in range(1,pickedNumber):
number = random.randint(20,50)
print(number)
sum += number
if number < smallest:
smallest = number
if number > largest:
largest = number
print('The sum = ',sum)
print('the average = ', "{:.2f}".format( sum/pickedNumber))
print('the largest = ', largest)
print('The smallest = ',smallest)