我正在尝试编写一个小片段,其中提示询问用户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的总和。
我该如何解决这个问题?
提前致谢!
答案 0 :(得分:3)
您应该将total
var初始化为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 + ".");
&#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 + ".");