gpt4 book ai didi

javascript - 无法让 JavaScript 程序添加奇数

转载 作者:行者123 更新时间:2023-12-03 04:30:03 25 4
gpt4 key购买 nike

问题是这样的:

创建一个求和程序,计算 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com