计算英文句子单词重量

计算英文句子单词重量

 1process.stdin.resume();  2process.stdin.setEncoding('utf-8');  3let input = '';  4  5process.stdin.on('data', (data) => {  6 input += data;  7});  8  9process.stdin.on('end', () => { 10 // 去除输入字符串两端的空白字符(包括换行符) 11 input = input.trim(); 12 13 // 调用待实现的函数 14 let averageWeight = doFunc(input); 15 16 // 输出结果 17 console.log(averageWeight); 18 19 process.exit(); 20}); 21 22/** 23 * 计算句子的平均重量 24 * @param {string} sentence - 输入的句子 25 * @returns {number} - 平均重量,四舍五入保留两位小数 26 */ 27function doFunc(sentence) { 28 // 将句子拆分为单词数组 29 let words = sentence.split(' '); 30 31 // 计算总重量和单词数量 32 let totalWeight = words.reduce((sum, word) => sum + word.length, 0); 33 let wordCount = words.length; 34 35 // 计算平均重量 36 let averageWeight = totalWeight / wordCount; 37 38 // 四舍五入保留两位小数 39 return averageWeight.toFixed(2); 40}
process.stdin.resume(); process.stdin.setEncoding('utf-8'); let input = ''; process.stdin.on('data', (data) => { input += data; }); process.stdin.on('end', () => { // 去除输入字符串两端的空白字符(包括换行符) input = input.trim(); // 调用待实现的函数 let averageWeight = doFunc(input); // 输出结果 console.log(averageWeight); process.exit(); }); /** * 计算句子的平均重量 * @param {string} sentence - 输入的句子 * @returns {number} - 平均重量,四舍五入保留两位小数 */ function doFunc(sentence) { // 将句子拆分为单词数组 let words = sentence.split(' '); // 计算总重量和单词数量 let totalWeight = words.reduce((sum, word) => sum + word.length, 0); let wordCount = words.length; // 计算平均重量 let averageWeight = totalWeight / wordCount; // 四舍五入保留两位小数 return averageWeight.toFixed(2); }

Powered By 可尔物语

浙ICP备11005866号-12