简单的 While 和 For 循环的问题

Trouble with simple While and For loop

本文关键字:循环 问题 For While 简单      更新时间:2023-09-26

我在下面的代码示例中遇到了一些问题,请耐心等待,仍然是初学者

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!");
}