开关盒中的各种选项

时间:2018-11-30 20:26:34

标签: c++ c

我试图用C进行测验。5个答案,只有一个是正确的。我正在使用开关。我的疑问是您是否拥有正确答案的数量以及正确答案的后果。但另一方面,我需要将其他4个错误。如何选择多个答案?是1,3,4,5吗? P.s.还有无效的选项,每种情况下我都需要一个字符串! pontos均值和p1是答案。谢谢

    switch (p1) {
    case 2 :
        correct answer
        pontos = pontos + 1;
        break;
    case 1, 3, 4, 5 :
        wrong answer
        pontos = pontos - 1;
    default :
        Invalid answer
        pontos = pontos - 1;
    }    

1 个答案:

答案 0 :(得分:5)

您可以使用相同的正文堆叠多个case语句,如下所示:

switch (foo) {
    case 1:
    case 2:
    case 3:
    case 5: {
        printf("Sorry, wrong answer.");
        break;
    }
    case 4: {
        printf("You got it right!");
        break;
    }
}

或者您可以仅使用default大小写来捕获所有不正确的内容:

switch (foo) {
    case 4: {
        printf("You got it right!");
        break;
    }
    default: {
        printf("Sorry, wrong answer.");
        break;
    }
}
相关问题