我正在尝试创建一个程序,该程序查找某人输入的一组数据的平均值。我尝试使用此代码:
var data = [];
var yesno = confirm("Would you like to add more data?");
while (yesno) {
var newdata = +prompt("Enter a piece of data (must be a number)");
data.push(newdata);
var yesno = confirm("Would you like to add more data?");
}
var total = 0;
var i = 0;
if (!yesno) {
while (i < data.length) {
total + data[i];
i++;
}
var average = total / data.length;
document.write(average);
}
但是,当我运行它时,无论我插入什么内容,它都始终显示“ 0”。预先感谢您的帮助。
答案 0 :(得分:4)
问题出在行
total + data[i];
此代码将在某些结果执行后生成。但是,那值什么都没有发生。在javascript中,数字是原始类型。除对象外,所有数据类型对象。您无法使用=
对它们进行突变(将它们分配为一个值)。
您需要使用赋值表达式。
total = total + data[i];
否则将是
total += data[i];
另一个问题是您没有将prompt()
的结果转换为Number
。使用Unary Plus +
将字符串转换为数字。
下面是代码的正确版本。
var data = [];
var yesno = confirm("Would you like to add more data?");
while (yesno) {
var newdata = +prompt("Enter a piece of data (must be a number)");
data.push(newdata);
var yesno = confirm("Would you like to add more data?");
}
var total = 0;
var i = 0;
if (!yesno) {
while (i < data.length) {
total += data[i];
i++;
}
var average = total / data.length;
document.write(average);
}
使用do-while
和reduce()
var data = [];
var yesno;
do{
var newdata = +prompt("Enter a piece of data (must be a number)");
yesno = confirm("Would you like to add more data?");
data.push(newdata);
}
while (yesno);
var total = data.reduce((ac,a) => ac + a,0);
var average = total / data.length;
document.write(average);
答案 1 :(得分:2)
total + data[i]
是一个“孤立的表达式”。使用=
或+=
。
var data = [];
var yesno = confirm("Would you like to add more data?");
while (yesno) {
var newdata = +prompt("Enter a piece of data (must be a number)");
data.push(newdata);
var yesno = confirm("Would you like to add more data?");
}
var total = 0;
var i = 0;
if (!yesno) {
while (i < data.length) {
total += data[i];
i++;
}
var average = total / data.length;
document.write(average);
}
答案 2 :(得分:1)
尝试一下:
var data = [];
var yesno = confirm("Would you like to add more data?");
while (yesno) {
var newdata = prompt("Enter a piece of data (must be a
number)");
data.push(newdata);
var yesno = confirm("Would you like to add more
data?");
}
var total = 0;
var i = 0;
if (!yesno) {
while (i < data.length) {
total += data[i];
i ++;
var average = total / data.length;
document.write(average);
}
}