这是问题所在:

创建一个求和程序,该程序计算介于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);

最佳答案

您已经创建了一个无限循环。确保每次迭代增加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);





为了提高效率,您可以将increase = increase + 1;更改为increase = increase + 2;。无需处理偶数。同样,tantalum应该设置为0才能启动。

关于javascript - 无法获取JavaScript程序以添加奇数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43528990/

10-10 22:50