为什么我的Javascript for循环连接数而不是添加?

时间:2017-07-02 11:45:46

标签: javascript for-loop math concatenation addition

我正在尝试编写一个小片段,其中提示询问用户5个数字并计算总数。

到目前为止,我有这个:

var counter, number, total;

for(counter = 0; counter < 5; counter++) {
  number = parseFloat(prompt("Enter a number:"));
  total += number;
}

document.write("The total is " + total + ".");

然而,'total'返回“”,例如,而不是15的总和。

我该如何解决这个问题?

提前致谢!

2 个答案:

答案 0 :(得分:3)

您应该将total var初始化为0:

&#13;
&#13;
var counter, number, total = 0;

for(counter = 0; counter < 5; counter++) {
  number = parseFloat(prompt("Enter a number:"));
  total += number;
}

document.write("The total is " + total + ".");
&#13;
&#13;
&#13;

答案 1 :(得分:2)

你必须将总数设置为0,如下所示:

var counter, number, total = 0;

for(counter = 0; counter < 5; counter++) {
  number = parseFloat(prompt("Enter a number:"));
  total += number;
}

document.write("The total is " + total + ".");