【前言】
今天在B站上看到小美老师的C语言关于成绩分类的实现方式,有两种,一种是if语句,另一种是swicth实现:
【题目】
跟着老师学习,使用两种方式来实现:
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
-
- int main(int argc, char *argv[]) {
- if (argc!= 2) {
- printf("Usage: %s <input_number>\n", argv[0]);
- return 1;
- }
-
- int num = atoi(argv[1]);
- printf("input:%d\n", num);
- int score = num/10;
- if(score>10 || score<0) {
- printf("Input number is too large.\n");
- return 1;
- };
-
- if(score>=9) {
- printf("Your grade is A.\n");
-
- }
- else if(score>=8) {
- printf("Your grade is B.\n");
-
- }
- else if(score>=7) {
- printf("Your grade is C.\n");
-
- }
- else if(score>=6) {
- printf("Your grade is D.\n");
-
- }
- else {
- printf("Your grade is E.\n");
-
- }
-
- switch(score) {
- case 10:
- printf("Your grade is A.\n");
- break;
- case 9:
- printf("Your grade is A.\n");
- break;
- case 8:
- printf("Your grade is B.\n");
- break;
- case 7:
- printf("Your grade is C.\n");
- break;
- case 6:
- printf("Your grade is D.\n");
- break;
- default:
- printf("Your grade is E.\n");
- }
- return 0;
-
- }
实现效果:
- PS D:\PL2303G_GPIOTest_v1003\PL2303G_GPIOTest_v1003_20230921\DLL> .\a.exe 91
- input:91
- Your grade is A.
- Your grade is A.
- PS D:\PL2303G_GPIOTest_v1003\PL2303G_GPIOTest_v1003_20230921\DLL> .\a.exe 88
- input:88
- Your grade is B.
- Your grade is B.
- PS D:\PL2303G_GPIOTest_v1003\PL2303G_GPIOTest_v1003_20230921\DLL> .\a.exe 45
- input:45
- Your grade is E.
- Your grade is E.
- PS D:\PL2303G_GPIOTest_v1003\PL2303G_GPIOTest_v1003_20230921\DLL>
大家感觉使用if与switch,哪种方式更好呢?