我在下面的代码示例中遇到了一些问题,请耐心等待,还是初学者
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代时,会打印
&#34;发电机#5开启,增加124兆瓦,总计310兆瓦!&#34;
但我需要它从第4行添加124,但它增加了64而不是第5代的124。
我错过了什么?我应该在for
循环之前进行计算吗?
答案 0 :(得分:0)
试试这个:
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(实际上是Generator 1的一个增量)然后再增加四次,总共增加五个增量而不是四个增量。
答案 1 :(得分:0)
[编辑]:
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;
}
试试这个。
答案 2 :(得分:-1)
以下是Working Fiddle:
使用
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!");
}