if-else statement

僤鯓⒐⒋嵵緔 提交于 2020-01-21 12:12:09

问题


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 compile these codes. The output has invalid in it too with the correct statement if it is more than 54.

For example :

  • if I enter in 55 it will say "OK" AND "Invalid".
  • if I enter in 54 it will just say "Moron".

Here are my codes:

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

void main()   
{
    int score;
    printf("Enter a Score");
    scanf("%d", &score);
    if (score >=80 && score <= 100){
        printf("Good\n",);
    }
     if (score >=55 && score <=79){
        printf("OK\n",);
    }
     if (score >=1 && score <=54){
        printf("Moron\n",);
    }
    else{
        printf("Invalid\n");
    }    
    system("pause");
}

回答1:


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.




回答2:


Each if statement is a standalone conditional statement. Your example has three groups of conditional statements:

  1. if (score >=80 && score <= 100)
  2. if (score >=55 && score <=79)
  3. if (score >=1 && score <=54) { ... } else { ... }

So if score has the value 55, it will match against #2 above and the else of #3.

One solution here would be to combine the above statements into one group. You can do this with else if.

e.g.

if (*expr*) {
    ...
} else if (*expr*) {
    ...
} else if (*expr*) {
    ...
} else {
    ...
}



回答3:


You have 2 if-else statements and both get executed. So you will do "something" for both of them. Walk through your code with score=55 and you'll find the problem.

2 solutions:

  1. Make the ifs "standalone" (so only one will pass)
  2. Add some elses to ensure only one of your branches executes.


来源:https://stackoverflow.com/questions/29908213/if-else-statement

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!