+ 1
How to can I use switch statement in this code?
/* A function that reads four arguments and returns the greatest of them.*/ #include <stdio.h> int max_of_four(int a, int b, int c, int d) { if(a>b && a>c && a>d) { // I want to add a switch statement here insted of if/else if. How can I do it so? return (a); } else if (b>a && b>c && b>d) { return (b); } else if (c>a && c>b && c>d) { return (c); } else { return (d); } } int main() { int a, b, c, d; scanf("%d %d %d %d", &a, &b, &c, &d); int ans = max_of_four(a, b, c, d); printf("%d", ans); return 0; }
1 Réponse
+ 4
A switch works with a expression that must be integral or enumerates type. Then compares that to a constant expression.
switch(expression){
case constant-expression:
statement(s);
break;
....
case default:
statement(s);
If you need to use switch:
int max_of_four(int a, int b, int c, int d){
Int max = 1;
If(b >= max)
max = 2;
If(c >= max)
max = 3;
If(d >= max);
max = 4;
switch(max){
case 1:
return a;
case 2:
return b;
...
}
}
It would probably be simpler to put. your integers into an array then sort them and return index 0.