7-30 计算4个整数的平均值
原题:
从键盘读入4个整数,输出平均值。
小贴士:所有符号是中文状态,Average中A是大写 ,除号不要写反了,/和\是不一样的。
输入格式:
10 20 30 25
输出格式:
Average为(10+20+30+25)/4=21.25
小数点保留2位小数。
.
解题思路:
- 导入 readline 模块,并创建一个接口对象 rl。
- 创建一个空数组 buf 用来存储输入的数据。
- 监听 ‘line’ 事件,当有新的输入行时,将输入内容添加到 buf 数组中。
- 监听 ‘close’ 事件,当输入结束时,执行回调函数。
- 在回调函数中,将 buf[0] 进行处理:
- 使用 split(/\s+/) 将字符串按空白字符拆分为数组,使得每个数字都成为数组的一个元素。
- 使用 map(Number) 将每个元素转换为数字类型。
- 使用 reduce() 方法对数组进行累加计算,得到数组中所有元素的总和。
- 将总和除以 4,得到平均值。
- 使用 toFixed(2) 方法将平均值保留两位小数。
- 使用字符串模板输出结果。
- 使用 console.log() 输出结果。
.
JavaScript(node)代码:
const r = require("readline");
const rl = r.createInterface({
input: process.stdin
});
let buf = [];
rl.on('line', (input) => {
buf.push(input);
});
rl.on('close', () => {
console.log(`Average为(${
buf[0].split(/\s+/).join("+")})/4=${
(buf[0].split(/\s+/).map(Number).reduce((sum, i) => sum + i) / 4).toFixed(2)}`);
});
.