我无法让我的开关功能工作

I can't get my switch function to work

本文关键字:开关 功能 工作 我的      更新时间:2023-10-16

问题是将1到10的所有值相加,不包括值3和6,但我不知道为什么我的开关函数没有过滤掉3和6。这是我的代码

#include <iostream>
using namespace std;
int main() 
{
    int a=1,total=0;
    while (a<=10)
    {
        a++;
        switch (a)
        {
            case 3:
                continue;
            case 6:
                continue;
            default:
                total = total + a;
        }
    }
    cout << "Sum of the total numbers are " << total << endl;
    return 0;
}

如果在while循环的末尾添加以下内容:

cout << "Current total: " << total << " a=" << a << endl;

问题会变得很清楚。你的输出会是这样的:

Current total: 2 a=2
Current total: 6 a=4
Current total: 11 a=5
Current total: 18 a=7
Current total: 26 a=8
Current total: 35 a=9
Current total: 45 a=10
Current total: 56 a=11
Sum of the total numbers are 56

正如你所看到的,它正确地跳过了3和6,但它缺少了1,并添加了11,这是我认为你没有预料到的两件事。

此外,您正在使用continue。对于switch语句,您希望使用break来阻止执行当前案例之后的案例。(详细说明一下,我认为continue会很好,因为我认为它正在做你想要的事情:将控制权转移回while语句。然而,如果a++在switch语句之后移动,这将不起作用。如果你在0启动a,如另一篇文章中所述,将条件更改为a < 10,那么你可以使用continue语句而不是break

如果您将a++;移到while循环的末尾并修复continue语句,我相信它会如您所期望的那样工作。

由于担心我的编辑可能会混淆问题,这里有两种替代方法可以构建代码以获得您想要的结果:

#include <iostream>
using namespace std;
int main() 
{
    int a=1,total=0;
    while (a<=10)
    {
        switch (a)
        {
            case 3:
                break;
            case 6:
                break;
            default:
                total = total + a;
        }
        a++;
    }
    cout << "Sum of the total numbers are " << total << endl;
    return 0;
}

#include <iostream>
using namespace std;
int main() 
{
    int a=0,total=0;
    while (a<10)
    {
        a++;
        switch (a)
        {
            case 3:
                continue;
            case 6:
                continue;
            default:
                total = total + a;
        }
    }
    cout << "Sum of the total numbers are " << total << endl;
    return 0;
}

您的代码工作正常,您在中心循环中只会犯一些小错误:a从2变为11,而不是从1变为10。应该是这样的:

int a=0, total=0;
while (a < 10)
{
    a++;
    // rest of code
}

编辑这样我的答案就更完整了。上面的修复将使您的代码正常工作,从而产生正确的结果,但正如@Pete所指出的,continue不是摆脱switchcase语句的方法。continue语句直接将您移回while循环的下一个循环。一个更好更干净的代码是这样的:

int a=0,total=0;
while (a < 10)
{
    a++;
    switch (a)
    {
        case 3:
            break;
        case 6:
            break;
        default:
            total = total + a;
    }
    // in every case you will get here; even if a==3 or a==6
}

编辑2如果你喜欢让一个从1到10的循环,这也是可能的:

int a=1,total=0;
while (a <= 10)
{
    switch (a)
    {
        case 3:
            break;
        case 6:
            break;
        default:
            total = total + a;
    }
    // in every case you will get here; even if a==3 or a==6
    a++;
}