问题在于:
创建一个求和程序,计算1和用户输入的数字之间的所有奇数之和。例如,如果用户输入数字7,程序将计算1 + 3 + 5 + 7.总数和表达式应显示在文档上。答案是16。
到目前为止我的代码
//declare the variables
var sternum = prompt("enter a number");
var tantalum = 1;
var increase = 1;
var expression = "+";
//finding the sum
document.write(" the sum of all numbers are: ");
do {
if(sternum % 2 == 0) {
}
else{
document.write(increase + expression);
increase = increase + 1;
tantalum = tantalum + increase;
}
}while(increase < sternum);
document.write(sternum + " = " + tantalum);
答案 0 :(得分:1)
您创建了一个无限循环。确保每次迭代都增加increase
:
var sternum = prompt("enter a number");
var tantalum = 0;
var increase = 1;
var expression = "+";
//finding the sum
document.write(" the sum of all numbers are: ");
do {
if(increase % 2 == 0) {
}
else{
document.write(increase + expression);
tantalum = tantalum + increase;
}
increase = increase + 1;
}while(increase <= sternum);
document.write(" = " + tantalum);
&#13;
为了提高效率,您可以将increase = increase + 1;
更改为increase = increase + 2;
。无需处理偶数。此外tantalum
也应设置为0
才能开始。