<!DOCTYPE html>
<html>
<body>
<script>
var cases=prompt("number of ingredients");
var i=0;
var a=[];
while (i<cases){
i=i+1;
var cost=prompt("cost of this ingredient");
a.push(cost);
}
alert(a);
var t=a.length;
var sum=0;
var j=0;
while (j<t-1){
var sum=sum+a[j];
j=j+1;
}
alert(sum);
</script>
</body>
</html>
想要根据“案例”中的用户输入创建数组。然后尝试找到数组'a'中所有数字的总和。但它没有给我答案。怎么了?感谢帮助。
答案 0 :(得分:0)
您应该将输入解析为整数,否则将其视为字符串。您还需要节点两次声明sum变量。也不需要变量t。
<!DOCTYPE html>
<html>
<body>
<script>
var cases=prompt("Number of ingredients");
var i = 0;
var a = [];
while (i < cases){
var cost = prompt("Cost of this ingredient");
a[i] = parseInt(cost);
i = i + 1;
}
var sum=0;
var j=0;
while (j < a.length){
sum=sum+a[j];
j=j+1;
}
alert(sum);
</script>
</body>
答案 1 :(得分:0)
优化版本:
var cases = parseInt(prompt("number of ingredients")), a = [], cost = 0;
while (cases--) {
var cost = prompt("cost of this ingredient");
a.push(parseInt(cost,10));
}
alert(a);
var len = a.length, sum = 0;
while (len--) {
sum += a[len];
}
alert(sum);