0
Maximum of two numbers by switch case code
Can someone please help me with a code to get a maximum of two numbers using a switch case code. I have been trying today and ended up using the following ; switch (number1 >number2) case 1: //codes case 0: //codes Although it runs it keeps warning me that the switch condition contains boolean value
8 Answers
+ 2
Hm.
You can always explicitly convert it:
(int)(n1>n2)
That should normally get rid of the warning.
+ 1
HonFu these last two solutions worked. Thanks
0
Did you really do this in C and not in C++?
I don't get a boolean warning, and I also didn't expect one either, since in C such an expression should be converted to 1 or 0 simply.
Maybe you should show us the actual code (this one wouldn't even run as it is written).
0
I did this in C en the actual... the warning is given by the compiler
0
Actual code..
int main (void)
{int num1, num2;
printf ("Enter two numbers:") ;
scanf ("%d%d", &num1, &num2) ;
if (num1!=num2)
{switch (num1 >num2)
{case 1:
printf ("%d is greater than %d. \n", num1, num2);
break ;
case 0:
printf ("%d is greater than %d.", num2, num1) ;
break;}
}
else
printf ("%d is equal to %d.", num1, num2) ;
return 0;
}
0
Converting switch (int) (num1 >num2) does not work
Sorry it worked I wrote switch (int) (num1>num2)
instead of switch ((int) num1 >num2)
0
When I have a problem like this, I try a minimalistic code snippet that expresses the shape I'm struggling with.
switch(3>4) {
case 1: printf("yep"); break;
case 0: printf("nope"); break;
}
If I run this here, it runs without problems.
And if I run this:
switch((int)3>4) {
case 1: printf("yep"); break;
case 0: printf("nope"); break;
}
It still works.
Can you try these in your environment and see if it works?
0
import java.util.Scanner;
class Switch{
public static void main(String[] args)
{
Scanner sc=new Scanner(System.in);
System.out.println("enter a integer");
int a=sc.nextInt();
System.out.println("enter a integer");
int b=sc.nextInt();
int c=(a>b)?1:0;
switch(c)
{
case 1:
System.out.println("a is greater");
break;
case 0:
System.out.println("b is greater");
break;
default:
System.out.println("invalid");
break;
}
}
}