我正在尝试创建一个程序,该程序可以找到某人输入的一组数据的平均值。我试过使用下面的代码:
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”。提前感谢您的帮助。
发布于 2019-06-02 08:34:59
问题出在这条线上
total + data[i];此代码将在某些结果将生成时执行。但随后该值不会发生任何变化。在javascript中,数字是基本类型。除对象以外的所有数据类型对象。你不能用=来改变它们(给它们赋值)。
您需要使用赋值表达式。
total = total + data[i]; 或者简称为
total += data[i]; 另一个问题是您没有将prompt()的结果转换为Number。使用一元加+将字符串转换为数字。
下面是你的代码的修正版本。
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);
发布于 2019-06-02 08:36:23
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);
}
发布于 2019-06-02 08:39:25
试试这个:
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);
}
}https://stackoverflow.com/questions/56411343
复制相似问题