int user_marks;
printf("Enter your obatined marks to know your grade: ")
scanf("%d", &user_marks);
switch (user_marks)
{
case user_marks>=90 && user_marks<=100:
printf("Your grade is A.");
break;
default:
printf("Enter valid marks.");
break;
}
I want to print that the user got an A grade if they enter numbers between 90 and 100 including those values in the "case" section of the code.
CodePudding user response:
cant use switch, use if / else
int user_marks;
printf("Enter your obatined marks to know your grade: ")
scanf("%d", &user_marks);
if(user_marks>=90 && user_marks<=100){
printf("Your grade is A.");
} else {
printf("Enter valid marks.");
}
CodePudding user response:
The case
labels must use integer constant expressions. This means that the result of these expressions must be known at compile-time. However, the value of user_marks
is not known at compile-time.
Even if user_marks
were an integer constant, the line
case user_marks>=90 && user_marks<=100:
would still be wrong, because, depending on the value of user_marks
, the expression user_marks>=90 && user_marks<=100
would evaluate to either 0
(false) or 1
(true), so the entire line would be equivalent to either
case 0:
or
case 1:
which is not what you want.
Therefore, if you really wanted to use a switch
statement, you would have to do the following instead:
switch (user_marks)
{
case 90:
case 91:
case 92:
case 93:
case 94:
case 95:
case 96:
case 97:
case 98:
case 99:
case 100:
printf("Your grade is A.");
break;
default:
printf("Enter valid marks.");
break;
}
However, it is simpler to use an if
...else
statement instead:
if ( user_marks >= 90 && user_marks <= 100 )
{
printf( "Your grade is A." );
}
else
{
printf( "Enter valid marks." );
}
CodePudding user response:
When the source data is particularly well understood, a "hashing function" can be used to determine a quality of that data.
The problem stated "only 90-100" are equivalent to "A", and the desire to use a switch()
statement.
The following tests several values in sequence, hashing them to a constant. (It's expected that values won't be greater than 100.
int my_main() {
int marks[] = { 70, 85, 89, 90, 94, 100 };
for( int i = 0; i < sizeof marks/sizeof marks[0] ; i ) {
int mark = marks[i];
// hash:
// leading 9 or 10 plus 1 => 10 or 11
// integer divide by 2 of result => 5
switch( ((mark / 10) 1) / 2 ) {
case 5:
printf( "%d is worth an A\n", mark );
break;
default:
printf( "%d is NOT worth an A\n", mark );
break;
}
}
return 0;
}
Output
70 is NOT worth an A
85 is NOT worth an A
89 is NOT worth an A
90 is worth an A
94 is worth an A
100 is worth an A
A simple if/else would be easier and clearer, of course...