首页 > 解决方案 > 切换 vs if ... else if ... else

问题描述

我有个问题。我正在为我的考试而学习,我不知道如何回答这个问题。基本上我必须将指令 if...else if... else 更改为指令开关,以使程序的输出保持不变。

void main()
{
    int x;
    x = 1;
    for (int i = 1; i < 10; ++i) {
        if (i <= 3)
            do {
                x += i;
                if (x >= 4)
                    break;
            } while (i % 2 == 0);
        else if ((i > 3) && (i < 5))
            x += 2;
        else
            continue;
    }
    while (x > 0) {
        printf(" x=%d ", x);
        x -= 1;
    }
    system("pause");
}

我可以在 for 循环内进行切换吗?

标签: c

解决方案


当然可以。循环控制语句for执行,块就是语句switch

鉴于它i在 1 到 9 的包含范围内,您可以将if块替换为

switch (i){
case 1: case 2: case 3:
    // that replaces 'if (i <= 3)'
    // ToDo - the code here
    break; // to obviate follow-through.
case 4:
    // that replaces 'if ((i > 3) && (i < 5))'
    // ToDo - the code here
    break;
default:
    // that replaces 'else'
    continue; // note that this is for the for loop, not the switch
}

请注意,此重构不会改变的if (x >= 4) break;行为。

然而,我不相信if用 a 替换块switch是正确的做法:边界i <= 3i >= 5不太自然地用 a 处理switch;也许改变ito的类型unsigned和显式处理case 0:会在一定程度上缓解这种情况。


推荐阅读