简单的 While 和 For 循环的问题
Trouble with simple While and For loop
我在下面的代码示例中遇到了一些问题,请耐心等待,仍然是初学者
var currentGen = 1;
var totalGen = 19;
var totalMW = 0;
totalMW = 62;
while (currentGen <= 4){
//Add 62 to the number of generators, beginning with Generator #1
console.log("Generator #" + currentGen + " is on, adding 62 MW, for a total of " + totalMW + " MW!");
totalMW = totalMW + 62;
currentGen++;
}
for (var currentGen = 5; currentGen <= totalGen; currentGen++){
//add 124 to generators #5 - 19
console.log("Generator #" + currentGen + " is on, adding 124 MW, for a total of " + totalMW + " MW!");
totalMW = totalMW + 124;
}
打印第 5 代时,它会打印
"发电机#5已开机,增加124兆瓦,总计310兆瓦!"
但是我需要它从第 124 行开始添加 4,但它在第 64 代中添加了 124 而不是第 5 代。
我错过了什么?我应该在for
循环之前进行计算吗?
试试这个:
var currentGen = 1;
var totalGen = 19;
var totalMW = 0;
while (currentGen <= 4){
//Add 62 to the number of generators, beginning with Generator #1
totalMW = totalMW + 62;
console.log("Generator #" + currentGen + " is on, adding 62 MW, for a total of " + totalMW + " MW!");
currentGen++;
}
for (var currentGen = 5; currentGen <= totalGen; currentGen++){
//add 124 to generators #5 - 19
totalMW = totalMW + 124;
console.log("Generator #" + currentGen + " is on, adding 124 MW, for a total of " + totalMW + " MW!");
}
这样,您可以从零开始,并在循环中执行所有加法。以前,您在第一个循环之前将totalMW
设置为 62,然后在循环内再次增加总数 - 因此在前四次迭代之后,您已设置为 62(生成器 1 实际上为一个增量),然后再增加四次,总共增加 5 个增量而不是 4 个。
[编辑]:
while (currentGen < 4){
//Add 62 to the number of generators, beginning with Generator #1
console.log("Generator #" + currentGen + " is on, adding 62 MW, for a total of " + totalMW + " MW!");
totalMW = totalMW + 62;
currentGen++;
}
for (var currentGen = 4; currentGen <= totalGen; currentGen++){
//add 124 to generators #5 - 19
console.log("Generator #" + currentGen + " is on, adding 124 MW, for a total of " + totalMW + " MW!");
totalMW = totalMW + 124;
}
试试这个。
这是工作小提琴:
用
while (currentGen <= 4){
//Add 62 to the number of generators, beginning with Generator #1
console.log("Generator #" + currentGen + " is on, adding 62 MW, for a total of " + totalMW + " MW!");
if(currentGen== 4) break;
totalMW = totalMW + 62;
currentGen++;
}
for (var currentGen = 5; currentGen <= totalGen; currentGen++){
//add 124 to generators #5 - 19
totalMW = totalMW + 124;
console.log("Generator #" + currentGen + " is on, adding 124 MW, for a total of " + totalMW + " MW!");
}
相关文章:
- Jquery图像循环问题
- JavaScript的循环问题,将值插入数组将不起作用
- 数学和循环问题
- Java脚本循环问题
- NetSuite行项目删除内部循环问题
- 附加仅适用于第一个子循环问题
- 简单的 do/while 循环无限循环问题
- Javascript 和 HTML5 循环问题
- 仅在jQuery函数内部循环问题
- 嵌套循环问题
- 谷歌地图标记的循环问题
- 函数在 For 循环问题中
- PHP while 循环问题在 iOS 5 Safari 中
- JavaScript 加载重置时间戳循环问题
- Jquery 循环问题
- 与jquery结合使用时的Javascript循环问题
- Javascript中的ID和for循环问题
- 无限滚动(mysql,php&js)循环问题
- Facebook查询循环问题
- jQueryrotate if else循环问题