【YM】C语言——if判断语句改写成switch语句
H3C笔试的一个题,大概意思就是把if判断语句改写成switch语句,不过if判断的是一个范围。具体数字记不太清了。例如x<5;5<=x<10;x>=10
int x,y;
scanf("%d",&x);
if(x<5) {
y=x;
printf("x=%d, y=x %d\n",x,y);
} else if(x<10) {
y=2*x-1;
printf("x=%d, y=2*x-1 %d\n",x,y);
} else {
y=3*x-11;
printf("x=%d, y=3*x-11 %d\n",x,y);
}
改写switch语句:
#include <stdio.h>
int main(void) {
int x, y;
int c;
scanf("%d", &x);
c=(x<5)*1+(x>=5&&x<10)*2+(x>=10)*3;
switch(c) {
case 1:
y = x;
printf("x=%d, y=x = %d\n",x,y);
break;
case 2:
y = 2*x-1;
printf("x=%d, y=2*x-1 = %d\n",x,y);
break;
case 3:
y = 3*x-11;
printf("x=%d, y=3*x-11 = %d\n",x,y);
break;
}
return 0;
}