设a为整型变量且其值大于零,请将以下if语句改写成switch语句。if(a<60)m=1;eles if(a>)
时间: 2023-05-27 21:02:58 浏览: 120
对不起,原来的代码有错误。以下是正确的if语句的改写:
```c++
switch(a) {
case 0:
case 1:
case 2:
case 3:
...
case 59:
m = 1;
break;
case 60:
case 61:
case 62:
case 63:
...
case 100:
m = 2;
break;
default:
break;
}
```
注:上述代码只是给出一种可行的方案,可能不是最优解。
相关问题
设a为整型变量且其值大于零,请将以下if语句改写成switch语句。
if(a == 1){
// do something
} else if(a == 2){
// do something
} else if(a == 3){
// do something
} else {
// do something
}
改写成switch语句:
switch(a){
case 1:
// do something
break;
case 2:
// do something
break;
case 3:
// do something
break;
default:
// do something
break;
}
设a为整型变量且其值大于零,请将以下if-else语句改写成switch语句,并完成整个程序的编写。 if ( a<60) m=1; else if(a<70) m=2; else if(a<80) m=3; else if(a<90) m=4; else m=5;
int m;
if (a < 60)
m = 1;
else if (a < 70)
m = ;
else if (a < 80)
m = 3;
else if (a < 90)
m = 4;
else
m = 5;
可以改写为:
int m;
switch(a/10) {
case 6:
m = 1;
break;
case 7:
m = 2;
break;
case 8:
m = 3;
break;
case 9:
m = 4;
break;
default:
m = 5;
break;
}
完整的程序代码如下:
#include <iostream>
using namespace std;
int main() {
int a;
int m;
cout << "请输入一个大于零的整数:";
cin >> a;
switch(a/10) {
case 6:
m = 1;
break;
case 7:
m = 2;
break;
case 8:
m = 3;
break;
case 9:
m = 4;
break;
default:
m = 5;
break;
}
cout << "m的值为:" << m << endl;
return 0;
}
阅读全文