我想将此switch语句转换为if / else和if / then语句。 我的Switch语句是:
char option;
printf("Choose your option : ");
scanf("%c",&option);
switch(option){
case 'a':
case 'A': a = 20 + 10 ;
printf("Addition process result:%d",a);
break;
case 'b':
case 'B': a = 20 - 10 ;
printf("Subtraction process result:%d",a);
break;
case 'c':
case 'C': a = 20 * 10 ;
printf("Multiplication process result:%d",a);
break;
case 'd':
case 'D': a = 20 + 10 ;
printf("Division process result:%d",a);
break;
default:
printf("Invalid option");
}
答案 0 :(得分:1)
您只是这样做:
if(option == 'a' || option == 'A') {
// do whatever
}
else if (option == 'b' || option == 'B') {
// do whatever
}
...如果不是,则为其他
然后对于“无效选项”,您只有一个else {}。如果第一个if或随后的else的任何一个if的评估结果为true,则将跳过所有其他if。
答案 1 :(得分:1)
像这样:
#include <stdio.h>
int main() {
char option;
printf("Choose your option : ");
scanf("%c",&option);
if (option == 'a' || option == 'A') {
int a = 20 + 10;
printf("Addition process result:%d", a);
} else if (option == 'b' || option == 'A') {
int a = 20 - 10;
printf("Subtraction process result:%d", a);
} else if (option == 'c' || option == 'C') {
int a = 20 * 10;
printf("Multiplication process result:%d", a);
} else if (option == 'd' || option == 'D') {
int a = 20 + 10;
printf("Division process result:%d", a);
} else {
printf("Invalid option");
}
return 0;
}