Switch语句甚至在中断后执行case 2

时间:2016-04-17 23:23:08

标签: c

当案例1时,程序执行预期的代码,但是当它询问你是否要再次计算音量时,如果你选择是,它只执行案例2.我不确定是什么问题。除非你在菜单中选择2,否则如何才能执行案例1?

        #include <stdio.h>
        #include <stdlib.h>

        int main()
        {
            float menu1, opt1, opt2, opt3, opt4, t;
            int td;

            printf("Enter: ");
            scanf("%d",&td);
        switch(td) {
            case 1:
            printf("Enter a, b, c, and h of the triangular prism in meters\n\n");
            printf("a ");
            scanf("%f", &opt1);
            printf("b ");
            scanf("%f", &opt2);
            printf("c ");
            scanf("%f", &opt3);
            printf("h ");
            scanf("%f", &opt4);
            printf("\nWould you like to make another Volume calculation (1 for Yes, 2 for No)?");
            scanf("%f", &menu1);
            if (menu1 == 2) {
                t = 0;
                break;
            }
            if (menu1 < 1 || menu1 > 2) {
                printf("\n\nUser choice must be between 1 and 2!\n\n");
                printf("Would you like to make another Volume calculation (1 for Yes, 2 for No)?");
                scanf("%f", &menu1);
                if(menu1 == 2) {
                   t = 0;
                   break;
                }
            }

        case 2:
            printf("Enter a and h of the triangular pyramid\n\n");
            printf("a ");
            scanf("%f", &opt1);
            printf("h ");
            scanf("%f", &opt2);
            printf("\nWould you like to make another Volume calculation (1 for Yes, 2 for No)?");
            scanf("%f", &menu1);
            if (menu1 == 2) {
                t = 0;
                break;
            }
            if (menu1 < 1 || menu1 > 2) {
                printf("\n\nUser choice must be between 1 and 2!\n\n");
                printf("Would you like to make another Volume calculation (1 for Yes, 2 for No)?");
                scanf("%f", &menu1);
                if(menu1 == 2) {
                   t = 0;
                   break;
                }
            }
    }
        }

1 个答案:

答案 0 :(得分:4)

break case 1:if语句仅在if块内 。如果case 1: // ... if (menu1 < 1 || (menu1 > 2) { // ... if (menu1 == 2) { t = 0; break; } } // BUG: there should be a break here case 2: // ... printf("Enter a and h of the triangular pyramid\n\n"); printf("a "); // ... 都不是 true ,那么你就会失败。

这是你原来的:

case 1:
    // ...
    if (menu1 < 1 || (menu1 > 2) {
        // ...
        if (menu1 == 2) {
            t = 0;
            break;
        }
    }
    break;  // FIX: this is your _missing_ break statement

case 2:
    // ...
    printf("Enter a and h of the triangular pyramid\n\n");
    printf("a ");
    // ...

这是固定代码:

.indexOf()