简体   繁体   English

将while循环转换为for循环会导致无限循环

[英]Converting while loop to for loop causes infinite loop

I've been having converting a while loop to a for loop.我一直在将 while 循环转换为 for 循环。 The problem I am having is the while loop works as intended, but when compiled the for loop causes an infinite loop.我遇到的问题是 while 循环按预期工作,但是编译时 for 循环会导致无限循环。 Any help would be awesome!任何帮助都是极好的!

int y1 = 1776;
int y2 = 2008;

while(y1 <= y2){
    ++ y1;
    if( (y1%400==0 || y1%100!=0) &&(y1%4==0))
        cout << y1 <<" "<< "Is a Leap Year" << " ";
}
cout <<"Now with a for loop" << endl;

for(y1 <= y2; ++ y1;)
{
    if( (y1%400==0 || y1%100!=0) &&(y1%4==0))
        cout << y1;
}

you are very close but:你非常接近,但是:

for(y1 <= y2; ++ y1;)
                   ^

should be:应该:

for(;y1 <= y2; ++ y1)
    ^

note that because you are skipping any initializing, ie the usual int i = 0 then you should make sure that its the first placer that is empty, not the last since for loops are structured like:请注意,因为您正在跳过任何初始化,即通常的int i = 0那么您应该确保它的第一个放置器是空的,而不是最后一个,因为 for 循环的结构如下:

for(initialize stuff here; boolean here; iterator here)
int y1 = 1776;
int y2 = 2008;

for(;y1 <= y2; ++y1)
{
    if( (y1%400==0 || y1%100!=0) &&(y1%4==0))
        cout << y1;

}

Since y1 has already a value, you can leave the initialization of the for loop empty.由于y1已经有一个值,您可以将for循环的初始化留空。

Your loop isn't complete.你的循环不完整。 It should look like:它应该看起来像:

for (int y1 = 0; y1 <= y2; y1++)

Please take the time to do a fast google search to see the right syntax for a for loop.请花时间进行快速的谷歌搜索,以查看for循环的正确语法。 Here it is : http://www.cplusplus.com/doc/tutorial/control/这是: http : //www.cplusplus.com/doc/tutorial/control/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM