switch case 例子
时间: 2023-06-07 13:08:14 浏览: 95
很好的问题!switch case是一种流程控制结构,它允许根据表达式的值选择执行不同的操作。下面是一个简单的例子:
```c
#include <stdio.h>
int main() {
int day = 1;
switch (day) {
case 1:
printf("Monday\n");
break;
case 2:
printf("Tuesday\n");
break;
case 3:
printf("Wednesday\n");
break;
case 4:
printf("Thursday\n");
break;
case 5:
printf("Friday\n");
break;
default:
printf("Invalid day\n");
}
}
```
在这个例子中,我们定义了一个整数变量day,它的值为1。然后我们使用switch语句对这个变量进行控制流处理。根据day的值,我们可以看到输出了"Monday"。如果day的值不是1到5之间的整数,就会输出"Invalid day"。
希望这个例子可以帮助你更好地理解switch case结构!
相关问题
switch case例子
可以回答这个问题。switch case是一种常见的控制流程结构,它根据一个变量的值来决定具体执行哪个分支。例如:
switch (num) {
case 1:
//执行代码块1
break;
case 2:
//执行代码块2
break;
default:
//执行默认代码块
}
以上是一个简单的switch case例子,当变量num的值为1时,执行代码块1;当变量num的值为2时,执行代码块2;当变量num的值既不是1也不是2时,执行默认代码块。
C#switch case例子
C#中的switch case语句可以用于多个离散值的判断,以下是一个简单的例子:
```
int num = 2;
switch(num)
{
case 1:
Console.WriteLine("这是数字1");
break;
case 2:
Console.WriteLine("这是数字2");
break;
case 3:
Console.WriteLine("这是数字3");
break;
default:
Console.WriteLine("这不是1、2、3中的任何一个数字");
break;
}
```
在这个例子中,我们定义了一个整型变量num,并使用switch case语句对其进行判断。当num等于1时,输出“这是数字1”;当num等于2时,输出“这是数字2”;当num等于3时,输出“这是数字3”;当num不等于1、2、3中的任何一个数字时,输出“这不是1、2、3中的任何一个数字”。需要注意的是,每个case后面必须要有break语句,否则程序会继续执行下去。
阅读全文
相关推荐
















