No error message appears when the user enters an invalid number

I created a simple program that works and now when I enter a number that is greater than "100 and less than 0" it should show an invalid message.

int math,eng,phy;
float f,h;
printf("Enter math marks:");
scanf("%d",&math);
if (math<0 && math>100)
{
    printf("You have entered invalid number");
}
printf("Enter eng marks:");
scanf("%d",&eng);
printf("Enter phy marks:");
scanf("%d",&phy);
f=math+eng+phy;
if (f>=90 && h<=100)
{
    printf(" You got A grade\n");
}
h=f/300*100;
printf("Your obtained marks=%f\n",f);
printf("Your  percentage=%f\n",h);
getch();
}

      

+3


source to share


3 answers


You must use if(math < 0 || math > 100)

... the number cannot be> 100 and <0 at the same time.



+5


source


There is no number that is greater than 100 and less than 0.

More than 100 = 101, 102, 103, 104

Less than 0 = -1, -2, -3



You see? If you only want to allow numbers from 0 to 100, you need:

if(x > 0 && x < 100){ /* Right number */ }

      

+4


source


Several problems are written in the program.

First, the math class score checks if the class matches less than 0 and more than 100 at the same time. This is not possible and will cause the program to never print the desired message, even if the math class variable is outside the required range.

if (math < 0 && math > 100)
    {
        printf("You have entered invalid number");

      

This can be fixed using the boolean || (or) instead of && (as well).

if (math < 0 || math > 100)
    {
        printf("You have entered invalid number");

      

The remaining problem is that only the math class is checked this way. A class check function can be written to make sure that English and physical grade classes are also in the correct range.

+2


source







All Articles