Question about C syntax
I have a friend who was working on a c example from a book and he did a code like
#include<stdio.h>
#include<math.h>
#pragma warning(disable:4996)
int main()
{
float numGrade;
printf("\n\nPlease enter your numerical grade: ");
scanf("%f", &numGrade);
if (numGrade >= 90)
printf("\nYou got an A.\n\n");
else if (90 > numGrade >= 80)
printf("\nYou got a B.\n\n");
else if (80 > numGrade >= 70)
printf("\nYou got a C.\n\n");
else if (70 > numGrade >= 60)
printf("\nYou got a D.\n\n");
else if (60 > numGrade)
printf("\nYou got an F.\n\n");
else
printf("\nThis is an invalid grade!\n");
}
Is there any problem with doing it like that or should he do it like :
int main()
{
float numGrade;
printf("\n\nPlease enter your numerical grade: ");
scanf("%f", &numGrade);
if (numGrade >= 90)
printf("\nYou got an A.\n\n");
else if (90 > numGrade && numGrade >= 80)
printf("\nYou got a B.\n\n");
else if (80 > numGrade && numGrade >= 70)
printf("\nYou got a C.\n\n");
else if (70 > numGrade && numGrade >= 60)
printf("\nYou got a D.\n\n");
else if (60 >开发者_Python百科 numGrade)
printf("\nYou got an F.\n\n");
else
printf("\nThis is an invalid grade!\n");
}
That first example won't work at all.
The first comparison in each test will return either 0 or 1. So it will always fail the second.
EDIT:
However, the program will probably still "work" the way it is desired, simply because the second comparison in each test is not needed.
精彩评论