关于数组求和、最大值、最小值、平均值。

时间:2021-02-06 15:10:53
const readline = require('readline-sync');//引入用户输入功能
console.log('请输入数组的长度:');//提示用户输入
let length = readline.question();//获取用户输入
let arr = [];//创建数组
for (let i = 0; i < length; i++) {
console.log(`请输入数组的第${i + 1}个数:`);
let input = readline.question() - 0;
arr.push(input);
}
console.log(arr);
let sum = 0;
let average = 0;


let flag = true;

while (flag) {
console.log('请选择:1.求最大值,2.求最小值,3.求和,4.求平均数');
let option = readline.question() - 0;
switch (option) {
case 1: {
arr.sort(function (a, b) {
return a - b;
})
max = arr[length - 1];
console.log(`最大值是:${max}`);
break;
}
case 2: {
arr.sort(function (a, b) {
return a - b;
})
min = arr[0];
console.log(`最小值是:${min}`);
break;
}
case 3: {
for (let i = 0; i < arr.length; i++) {
sum = sum + arr[i];
}
console.log(`和为:${sum}`);
sum = 0;
break;
}
case 4: {
for (let i = 0; i < arr.length; i++) {
sum = sum + arr[i];
average = sum / arr[i];
}
console.log(`平均数为:${average}`);
sum = 0;
flag = false;
break;
}
}
}