欢迎光临
我们一直在努力

switch c语言怎么用

switch语句是C语言中的一种控制结构,用于根据表达式的值进行多路分支。switch语句的基本格式如下:switch(表达式){case 常量表达式1:语句1break;case 常量表达式2:语句2break;default:语句n+1}表达式的值与常量表达式的值进行比较,如果相等则执行对应的语句。如果没有匹配的常量表达式,则执行default后面的语句。注意,每个case后面都需要加上break语句,以避免执行下一个case中的语句 。

C语言中使用switch语句

switch语句简介

switch语句是C语言中的一种多分支选择结构,它根据表达式的值来选择执行相应的代码块,switch语句可以替代多个if-else语句,使代码更加简洁易读。

switch语句的语法

switch (expression) {
    case constant1:
        // 当expression等于constant1时执行的代码
        break;
    case constant2:
        // 当expression等于constant2时执行的代码
        break;
    ...
    default:
        // 当expression不等于任何case常量时执行的代码
}

switch语句的使用实例

1、判断一个整数的奇偶性

include <stdio.h>
int main() {
    int num;
    printf("请输入一个整数:");
    scanf("%d", &num);
    switch (num % 2) {
        case 0:
            printf("%d是偶数。
", num);
            break;
        case 1:
            printf("%d是奇数。
", num);
            break;
        default:
            printf("输入错误。
");
    }
    return 0;
}

2、根据用户输入的成绩评级

include <stdio.h>
int main() {
    int score;
    printf("请输入你的成绩(0-100):");
    scanf("%d", &score);
    switch (score / 10) {
        case 10:
        case 9:
            printf("优秀。
");
            break;
        case 8:
            printf("良好。
");
            break;
        case 7:
            printf("中等。
");
            break;
        case 6:
            printf("及格。
");
            break;
        default:
            printf("不及格。
");
    }
    return 0;
}

3、实现一个简单的计算器,支持加、减、乘、除四种运算

include <stdio.h>
include <stdlib.h>
include <math.h>
include <string.h>
include <stdbool.h>
include <conio.h>
include <windows.h>
include <time.h>
include <map>
include <vector>
include <algorithm>
include <functional>
include <iomanip>
include <sstream>
include <iostream>
include <cstring>
include <queue>
include <list>
include <stack>
include <set>
include <unordered_map>
include <unordered_set>
include <tuple>
include <bitset>
include <numeric> // std::accumulate, std::inner_product, std::iota, etc.) in C++17 and later versions. If you want to use these features, you need a compiler that supports at least C++11. For example, Visual Studio Community Edition 2019 supports C++17. However, it is recommended to use the latest version of Visual Studio or other popular compilers for better compatibility and performance.
赞(0) 打赏
未经允许不得转载:九八云安全 » switch c语言怎么用

评论 抢沙发