迭代循环回路

继续

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;

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值