switch语句C ++
时间: 2023-10-30 18:09:36 浏览: 39
switch语句是一种流程控制语句,用于根据不同的条件执行不同的代码块。它的基本语法如下:
```
switch (expression) {
case value1:
// code block
break;
case value2:
// code block
break;
...
default:
// code block
break;
}
```
其中,expression 是要进行比较的表达式,value1、value2 等是要比较的值,case 后面跟的是要比较的值,如果 expression 的值等于某个 case 后面的值,则执行该 case 后面的代码块。如果没有任何一个 case 的值与 expression 的值相等,则执行 default 后面的代码块。
相关问题
C语言用switch语句实现+ - * / %运算
可以使用switch语句实现基本的加减乘除取余运算,示例代码如下:
```c
#include <stdio.h>
int main() {
int a, b;
char op;
printf("请输入第一个数:");
scanf("%d", &a);
printf("请输入操作符(+、-、*、/、%%):");
scanf(" %c", &op);
printf("请输入第二个数:");
scanf("%d", &b);
switch (op) {
case '+':
printf("%d + %d = %d\n", a, b, a + b);
break;
case '-':
printf("%d - %d = %d\n", a, b, a - b);
break;
case '*':
printf("%d * %d = %d\n", a, b, a * b);
break;
case '/':
if (b == 0) {
printf("除数不能为0\n");
} else {
printf("%d / %d = %d\n", a, b, a / b);
}
break;
case '%':
if (b == 0) {
printf("除数不能为0\n");
} else {
printf("%d %% %d = %d\n", a, b, a % b);
}
break;
default:
printf("无效的操作符\n");
break;
}
return 0;
}
```
在这个示例中,我们根据用户输入的操作符使用switch语句进行不同的运算。当除数为0时,我们需要特别处理以避免程序出错。
c语言switch+case语句
switch case语句是一种用于多分支选择的控制语句。它根据一个表达式的值,选择执行与该值相关的代码块。switch case语句的基本语法如下:
```
switch (expression)
{
case constant1:
// 对应 constant1 的代码块
break;
case constant2:
// 对应 constant2 的代码块
break;
...
default:
// 默认情况下的代码块
break;
}
```
expression是一个可以求值为整数或枚举类型的表达式。程序会依次检查每个case的常量值是否与expression的值相等,如果匹配则执行相应的代码块,并且遇到break语句会跳出switch语句。如果没有匹配的case,那么会执行default代码块(可选)。
以下是一个示例,演示如何使用switch case语句:
```c
#include <stdio.h>
int main()
{
int num = 2;
switch (num)
{
case 1:
printf("Number is 1\n");
break;
case 2:
printf("Number is 2\n");
break;
case 3:
printf("Number is 3\n");
break;
default:
printf("Number is not 1, 2 or 3\n");
break;
}
return 0;
}
```
输出结果是:Number is 2。
相关推荐
![pptx](https://img-home.csdnimg.cn/images/20210720083543.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)