switch case例子
时间: 2023-10-20 18:06:14 浏览: 63
可以回答这个问题。switch case是一种常见的控制流程结构,它根据一个变量的值来决定具体执行哪个分支。例如:
switch (num) {
case 1:
//执行代码块1
break;
case 2:
//执行代码块2
break;
default:
//执行默认代码块
}
以上是一个简单的switch case例子,当变量num的值为1时,执行代码块1;当变量num的值为2时,执行代码块2;当变量num的值既不是1也不是2时,执行默认代码块。
相关问题
switch case 例子
Sure, I'd be happy to help you with that! A switch case example is a programming construct that allows you to select one option from several choices based on the value of a variable. Here is an example:
```c
int main() {
int choice = 3;
switch(choice) {
case 1:
printf("You selected choice 1\n");
break;
case 2:
printf("You selected choice 2\n");
break;
case 3:
printf("You selected choice 3\n");
break;
default:
printf("Invalid choice\n");
}
return 0;
}
```
In this example, the program selects one of several options based on the value of the variable "choice". If "choice" is 1, the program outputs "You selected choice 1", and so on. If "choice" is not one of the given options, the default option outputs "Invalid choice".
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语句,否则程序会继续执行下去。
阅读全文
相关推荐














