随机生成10个数,赋给一维数组,求出一维数组的max、min、求和、平均值,并且改写成一个方法
时间: 2024-05-30 10:16:35 浏览: 10
import random
def array_stats(n):
arr = [random.randint(1, 100) for i in range(n)]
max_num = max(arr)
min_num = min(arr)
total = sum(arr)
avg = total / n
return max_num, min_num, total, avg
max_num, min_num, total, avg = array_stats(10)
print("Max number:", max_num)
print("Min number:", min_num)
print("Total:", total)
print("Average:", avg)
相关问题
随机生成10个数,赋给一维数组,求出一维数组的max、min、求和、平均值java
以下是Java代码实现:
```
import java.util.Random;
public class Main {
public static void main(String[] args) {
int[] arr = new int[10]; // 定义长度为10的一维数组
Random random = new Random(); // 创建随机数生成器
// 生成随机数并填充数组
for (int i = 0; i < arr.length; i++) {
arr[i] = random.nextInt(100); // 随机数范围在0-99之间
}
// 计算max、min、求和、平均值
int max = arr[0], min = arr[0], sum = 0;
double avg;
for (int i = 0; i < arr.length; i++) {
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
sum += arr[i];
}
avg = (double) sum / arr.length;
// 输出结果
System.out.println("数组元素为:");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
System.out.println("\nmax = " + max);
System.out.println("min = " + min);
System.out.println("sum = " + sum);
System.out.println("avg = " + avg);
}
}
```
运行结果示例:
```
数组元素为:
14 27 2 76 72 83 72 69 11 27
max = 83
min = 2
sum = 453
avg = 45.3
```
随机生成十个数赋给一维数组
以下是Python代码示例:
```python
import random
# 生成随机数并存入数组
arr = []
for i in range(10):
num = random.randint(1, 100)
arr.append(num)
# 输出数组
print(arr)
```
运行结果可能如下:
```
[63, 17, 51, 85, 89, 91, 73, 18, 27, 62]
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)