继续
continue语句提供了一个便捷的方式跳回到一个循环比正常的顶部,可用于一个迭代循环回路的余数。这是用一个例子来继续:
|
1
2
3
4
5
6
7
8
|
for
(int
iii=0; iii < 20; iii++){ //
if the number is divisible by 4, skip this iteration if
((iii % 4) == 0) continue; cout
<< iii << endl; |
这个程序打印所有的数量从0到19,不能被4整除。
使用时要小心,继续,或做循环。因为这些线圈通常迭代循环变量在循环体中,继续使用会导致环成为无限!考虑下面的程序:
|
1
2
3
4
5
6
7
8
|
int
iii=0;while
(iii < 10){ if
(iii==5) continue; cout
<< iii << "
"; iii++; |
这项计划的目的是打印0和9之间的每一个数除5。但实际上版画:
0 1 2 3 4
然后进入一个无限循环。当III是5,如果陈述是真实的,和环路返回顶部。三是不会增加。因此,在下一关,III仍然是5,如果声明是真实的,并计划继续永远循环。
使用break和continue
许多教科书警告读者不要使用break和continue因为它使执行流跳跃。这当然是真实的,并继续打破明智地使用可以使循环更加可读。例如,下面的程序打印所有的数字从0到99这是不整除3或4,并打印出多少数被发现符合此标准的:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
int
nPrinted = 0;for
(int
iii=0; iii < 100; iii++){ //
messy! if
((iii % 3) && (iii % 4)) { cout
<< iii << endl; nPrinted++; }}cout
<< nPrinted << "
numbers were found"
<< endl; |
|
1
2
3
4
5
6
7
8
9
10
11
12
13
|
int
nPrinted = 0;for
(int
iii=0; iii < 100; iii++){ //
if the number is divisible by 3 or 4, skip this iteration if
((iii % 3)==0 || (iii % 4)==0) continue; cout
<< iii << endl; nPrinted++;}cout
<< nPrinted << "
numbers were found"
<< endl; |
1万+

被折叠的 条评论
为什么被折叠?



