Code always gives same answer.

I'm making a grading program but whatever score I put I always says "Your grade is A." I've checked it over and over again but can't find a problem. Probably a silly mistake like I always do.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
 #include <stdio.h>

int main(void)
{
	int score;
	
	printf("The grading criteria is as follow:\n\n");
	
	printf("If your scores is between 90 and 100 then your grade is A.\n");
	printf("If your scores is between 80 and 90 then your grade is B.\n");
	printf("If your scores is between 70 and 80 then your grade is C.\n");
	printf("If your scores is between 50 and 70 then your grade is D.\n");
	printf("If your scores is less than 50 then your grade is F.\n\n\n");
	
	printf("Enter your score.\n");
	scanf("%d", &score);
	
	if(score>=90, score<=100)
	{
		printf("Your grade is A.");
    }
    
    else if(score>=80, score<=90)
	{
		printf("Your grade is B.");
    }
    
    else if(score>=70, score<=80)
	{
		printf("Your grade is C.");
    }
    
    else if(score>=50, score<=70)
	{
		printf("Your grade is D.");
    }
    
    else
	{
		printf("Your grade is F.");
    }
	
	
	getch();
	
}
You are misunderstanding the comma operator. You can't use it like that in this circumstance: All it does is report if your grade is less than or equal to 100. Use '||' (or) instead:
1
2
3
4
5
6
7
8
9
/* ... */
int main() {
    /* ... */
    if (score >= 90 || score <= 100)
        /* ... */
    else if (score >= 80 || score < 90)
        /* ... */
    /* ... */
}
Last edited on
Or you can use only the first condition.

1
2
3
4
5
if(score>=90) // this filters out grades >=90
{
	printf("Your grade is A.");
}    
else if(score>=80) // since grades >=90 have already been filtered out, this will get grades >=80 and < 90 


AND (&&), not OR (||).

The problem with OR is that if the score is 90 or more, then the OR is true, but if score is 100 or less, then the OR is again true. In other words, whatever the score, the first IF is true.


There is more. What if score is exactly 80? Should it give B or C? Even if you had the proper AND in the conditions, both would in principle match. Only through the IF..ELSE IF logic the 80 would yield B and skip the C.

This logic can be exploited. IF we laready know that the score cannot be more than 80 (the previous IFs have failed), we don't have to test it any more for the C.
because you are using comma , the parenthesis of if statement is not a parameter.
you should use bool AND && or bool OR || if you are comparing 2 or more statement.

Last edited on
Oops, yeah, my mistake. Not thinking clearly today...
aw :( my idol NT3 got beaten :((
Topic archived. No new replies allowed.