用java script 求数组的最大值、最小值、和、平均数

let readline = require(`readline-sync`);
console.log(`请输入数组的长度`);
let length = ~~readline.question(``);
let arr = [];
let sum = 0;
let average = 0;
for (let i = 0; i < length ; i++) {
console.log(`请输入第` + (i + 1) + `项的值:`);
arr[i] = parseFloat(readline.question(``));
sum += arr[i];
average = parseFloat(sum / length );
}
console.log(`请选择要执行的操作:1.求最大值 2.求最小值 3.求和 4.求平均数`);
let num = ~~readline.question(``);
arr.sort(function (j, k) { return j - k; });
if (num === 1) {
console.log(`最大值为:` + arr[arr.length - 1]);
} else if (num === 2) {
console.log(`最小值为:` + arr[0]);
}
else if (num === 3) {
console.log(`求和的值为:` + sum);
} else if (num === 4) {
console.log(`平均值为:` + average);
}

转载于:https://www.cnblogs.com/huangshan-0809/p/9656842.html

你可能感兴趣的:(java)