首页 > 解决方案 > 如何在不使用列表或任何其他数据结构的情况下打印最小和最大数量的 n 个随机数

问题描述

程序应该从用户那里读取一个正整数 n 来决定要生成多少个数字。随机数应在区间 [1, 100] 内。然后我应该打印平均值、最小值和最大值。但不使用列表或任何其他数据结构。我设法得到平均值,但我仍然需要得到最小和最大。有什么建议吗?

这是我的代码到目前为止的样子

标签: python

解决方案


您可以使用内置的 min() 和 max() 函数。这是一些代码,应该很容易解释:

import random

n = 20

# set up the values 
smallest = 101
biggest  = -1

for i in range(n):
    x = random.randint(1,100)
    
    # take the smallest of the new random number and the current smallest
    smallest = min(x, smallest)
    
    # take the biggest of the new random number and the current biggest
    biggest  = max(x, biggest)
    
print(smallest, biggest)

推荐阅读