If-else statement
My codes allow the user to enter 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 result is also invalid in this case with the correct instruction if it is greater than 54.
For example:
- if I enter 55 it will say OK and Wrong.
- If I go to 54, he'll 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");
}
source to share
This is because instead of using one control thread, you are using several (so if the condition is met before the last control thread if
( score >= 55
through score <= 100
), the code else
from the last one is also executed). You can use branches else if
:
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
/ operators else
, but the solution above seems less cumbersome.
source to share
Each statement if
is a stand-alone conditional statement. Your example has three groups of conditional statements:
-
if (score >=80 && score <= 100)
-
if (score >=55 && score <=79)
-
if (score >=1 && score <=54) { ... } else { ... }
So, if score
it matters 55
, it will match # 2 above and else
from # 3.
One solution here would be to combine the above statements into one group. You can do this with else if
.
eg.
if (*expr*) {
...
} else if (*expr*) {
...
} else if (*expr*) {
...
} else {
...
}
source to share
You have 2 statements if-else
and both are executed. Therefore, you will do "something" for both of them. Go through your code with help score=55
and you will find this problem.
2 solutions:
- Make it
if
"offline" (only one will go this way) - Add a few
else
to ensure that only one of your branches is executed.
source to share