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.
原创文章,作者:K-seo,如若转载,请注明出处:https://www.kdun.cn/ask/262579.html