从If语句切换到Switch语句

时间:2019-12-19 22:42:35

标签: c

是否可以使用任何信息或示例来帮助我将代码流从使用If语句更改为切换用例语句?

#include <stdio.h>

int main(void){
    double averageGrade;

    printf("\nThe average grade is:");
    scanf("%1f", &averageGrade);

    // output appropriate message for average grade
    if (averageGrade > 3.5) {
        printf("Average grade is A");
    }
    else if(averageGrade > 2.5) {
        printf("Average grade is B");
    }
    else if (averageGrade > 1.5) {
        printf("Average grade is C");
        }
    else if (averageGrade > 0.5) {
        printf("Average grade is D");
    }
    else {
        printf("Average grade is F");
    }
    return 0;
}

2 个答案:

答案 0 :(得分:1)

建议不使用if-else if语句链也不使用switch语句。

以下代码可以很好地实现这些要求。

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

struct grades
{
    double avgGrade;
    char  letGrade;
};

int main(void)
{
    double testAverageGrade;

    printf("\nEnter the average grade: ");
    if( scanf("%lf", &testAverageGrade) != 1 )
    {
        fprintf( stderr, "scanf for average grade failed\n" );
        exit( EXIT_FAILURE );
    }

    // implied else, scanf successful


    struct grades gradesTbl[] =
    {
        {  3.5, 'A' },
        {  2.5, 'B' },
        {  1.5, 'C' },
        {  0.5, 'D' },
        {  0.0, 'F' },
    };

    size_t numGrades = sizeof( gradesTbl ) / sizeof( gradesTbl[1] );

    for( size_t i=0; i<numGrades; i++ )
    {
        if( testAverageGrade > gradesTbl[i].avgGrade )
        {
            printf("Average grade is %c\n", gradesTbl[i].letGrade);
            break;
        }
    }
}

答案 1 :(得分:0)

您的案件没有特殊信息,但是您可以执行以下操作:

int iGrade = (int) floor(averageGrade - 0.5)
if(iGrade > 3) {
    iGrade = 3
}

switch(iGrade) {
    case 3:
       // code for A
       break;
    case 2:
       // code for B
       break;
    case 1:
       // code for C
       break;
    case 0:
       // code for D
       break;
    default:
       // code for F
       break;
}