if-else statement

前端 未结 3 607
-上瘾入骨i
-上瘾入骨i 2021-01-21 08:57

My codes allows the user to enter in a score from 1 to 100, which will either tell them that the score is \"Good\", \"OK\", \"Moron\", or \"Invalid\".

But, when I compil

3条回答
  •  生来不讨喜
    2021-01-21 08:59

    It is happening because instead of using one control flow you use multiple (thus if condition is met before the last if control flow (score >= 55 through score <= 100), else code from the last one is also executed). You can use else if branches:

    if (score >= 80 && score <= 100){
       printf("Good\n",);
    } else if (score >= 55 && score <= 79){
       printf("OK\n",);
    } else if (score >= 1 && score <= 54){
       printf("Moron\n",);
    } else {
       printf("Invalid\n");
    }
    

    You can also use nested if/else statements, but the solution above seems less cumbersome.

提交回复
热议问题