c语言switch语句编程题(c语言中switch语句的用法)

1. Introduction

Switch statement is a powerful construct in the C programming language that allows conditional control flow based on the value of an expression. It provides an efficient alternative to multiple if-else statements when dealing with multiple cases. In this article, we will explore some interesting programming questions related to switch statements in C.

2. Question 1: Grade Calculation

Suppose you have a variable "score" that stores the score obtained by a student in an exam. Write a program to calculate the corresponding grade based on the following criteria:

  • If the score is greater than or equal to 90, the grade is "A".
  • If the score is between 80 and 89, the grade is "B".
  • If the score is between 70 and 79, the grade is "C".
  • If the score is between 60 and 69, the grade is "D".
  • If the score is less than 60, the grade is "F".

Using switch statement, we can easily solve this problem:


#include

int main() {
int score;
char grade;

printf("Enter the score: ");
scanf("%d", &score);

switch(score/10) {
case 10:
case 9:
grade = 'A';
break;
case 8:
grade = 'B';
break;
case 7:
grade = 'C';
break;
case 6:
grade = 'D';
break;
default:
grade = 'F';
break;
}

printf("Grade: %c\n", grade);

return 0;
}

3. Question 2: Month Name

Write a C program to print the name of a month based on its number. For example, if the number is 1, the program should print "January". If the number is 5, it should print "May". If the number is not between 1 and 12, it should print "Invalid month number". This can be easily achieved using a switch statement:


#include

int main() {
int month;

printf("Enter the month number: ");
scanf("%d", &month);

switch(month) {
case 1:
printf("January\n");
break;
case 2:
printf("February\n");
break;
case 3:
printf("March\n");
break;
case 4:
printf("April\n");
break;
case 5:
printf("May\n");
break;
case 6:
printf("June\n");
break;
case 7:
printf("July\n");
break;
case 8:
printf("August\n");
break;
case 9:
printf("September\n");
break;
case 10:
printf("October\n");
break;
case 11:
printf("November\n");
break;
case 12:
printf("December\n");
break;
default:
printf("Invalid month number\n");
break;
}

return 0;
}

In conclusion, switch statement in C provides a concise way to handle multiple cases based on the value of an expression. It allows us to avoid the verbosity of multiple if-else statements and makes the code more readable. The two programming questions discussed in this article are just some examples of how switch statement can be used effectively in real-world scenarios.

本文来自投稿,不代表亲测学习网立场,如若转载,请注明出处:https://www.qince.net/cyye8ou1iq.html

郑重声明:

本站所有内容均由互联网收集整理、网友上传,并且以计算机技术研究交流为目的,仅供大家参考、学习,不存在任何商业目的与商业用途。 若您需要商业运营或用于其他商业活动,请您购买正版授权并合法使用。

我们不承担任何技术及版权问题,且不对任何资源负法律责任。

如遇到资源无法下载,请点击这里失效报错。失效报错提交后记得查看你的留言信息,24小时之内反馈信息。

如有侵犯您的版权,请给我们私信,我们会尽快处理,并诚恳的向你道歉!

(0)
上一篇 2023年7月28日 下午3:22
下一篇 2023年7月28日 下午3:23

猜你喜欢