如何在 javascript 中实现带有偏差的平均年龄? 我需要制作一个 Javascript 算法:
- 询问10个人的姓名和年龄;
- 打印人的“平均年龄”屏幕;
- 打印每个人的姓名和年龄与平均值的偏差。
我试着一个一个地写每个提示,但想知道是否有办法缩短这段代码
var input = prompt('Enter your name');
var name1 = input;
input = prompt('Enter your age:');
var age1 = parseInt (input);
var input = prompt('Enter your name');
var name2 = input;
input = prompt('Enter your age:');
var age2 = parseInt (input);
[...]
var input = prompt('Enter your name');
var name10 = input;
input = prompt('Enter your age:');
var age10 = parseInt (input);
var average = (age1+age2+age3+age4+age5+age6+age7+age8+age9+age10/10);
console.log(`Average age: ${average}`);
console.log(`Name: ${name1}, Age: ${age1}, Deviance: ${deviance1}`);
console.log(`Name: ${name2}, Age: ${age2}, Deviance: ${deviance2}`);
[...]
console.log(`Name: ${name10}, Age: ${age10}, Deviance: ${deviance10}`);
我不知道如何做偏差(分析值与平均值的差异)
最佳答案
下面的另一个解决方案。我在代码中添加了一些注释以提供帮助。 如果您有任何问题,请告诉我:)
const MAX_NAMES = 3;
// Each person will be stored in this array below
let people = [];
// Store the total combined age in totalAge variable
let totalAge = 0;
for(let i = 0; i < MAX_NAMES; i++) {
let nameValue = prompt('Enter your name');
let ageValue = parseInt(prompt('Enter your age'));
// Add to the total age
totalAge += ageValue;
// we add an object to the array. 'name' and 'age' are the object Keys. We reference the keys to get the values back from the object later
people.push({ name: nameValue, age: ageValue })
}
// Print the Average Age of People
let averageAge = Math.round(totalAge / people.length);
console.log(`The average age is ${averageAge}`);
//Print each person's name and deviation from age to average.
for(let person in people) {
console.log(`Name: ${people[person].name} Deviation: ${Math.abs(people[person].age - averageAge)}`);
}
关于javascript - 如何在 javascript 中实现有偏差的平均年龄?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57405135/