如何使转换语句接受百分比而不是字母等级?

时间:2018-11-04 20:07:05

标签: c

我正在尝试弄清楚如何让用户输入一个百分比并让其吐出一个字母等级。当我运行该程序时,它甚至都不会进入案例。

期望的输入:请输入您的等级:70 预期输出:您得到了C!

#include <stdio.h>

int main(void)
{
    int percent;
    printf("Please enter your grade: ");
    scanf("%d", &percent);

    switch (percent)
    {

        case 1:
            (percent >= 90);
            puts("You got an A!");
            break;

        case 2:
            (percent >= 80);
            puts("You got a B!");
            break;

        case 3:
            (percent >= 70);
            puts("You got a C!");
            break;

        case 4:
            (percent >= 60);
            puts("You got a D!");
            break;

        case 5:
            (percent < 60);
            puts("You got an F!");
            break;
    }
}

2 个答案:

答案 0 :(得分:3)

类似的事情可能起作用。情况10和9失败,情况5、4、3、2、1和0失败。

@rici指出,%在这里不起作用,但/可以。

#include <stdio.h>

int main ( void){
    char input[100] = "";
    int percent = 0;
    int result = 0;

    do {
        printf("Please enter your grade 0 to 100: " );
        if ( fgets ( input, sizeof input, stdin)) {
            result = sscanf ( input, "%d", &percent);
        }
        else {
            fprintf ( stderr, "fgets EOF\n");
            return 0;
        }
    } while ( result != 1 || percent < 0 || percent > 100);

    switch( percent / 10){

        case 10:
        case 9:
            puts ("You got an A!");
            break;

        case 8:
            puts ("You got a B!");
            break;

        case 7:
            puts ("You got a C!");
            break;

        case 6:
            puts ("You got a D!");
            break;

        case 5:
        case 4:
        case 3:
        case 2:
        case 1:
        case 0:
            puts ("You got an F!");
            break;
    }

}

答案 1 :(得分:3)

这不是switch语句的地方;这是if / else阶梯的理想场所。

if (percent >= 90) {
    puts("You got an A!");
} else if (percent >= 80) {
    puts("You got a B!");
} else if (percent >= 70) {
    puts("You got a C!");
} else if (percent >= 60) {
    puts("You got a D!");
} else {
    puts("You got an F!");
}