① switch实现多分支程序设计 采用switch语句编写程序,实现百分制成绩转化为五级制成绩,如90到100分之间的为A,80到89之间为B,70到79为C,60到69为D,其他为E(P36)。
时间: 2024-11-25 09:15:12 浏览: 27
在许多编程语言中,包括C、C++、Java等,`switch`语句是一种有效的方式来组织多分支结构。下面是一个简单的例子,展示如何使用`switch`来将百分制成绩转化为五级制成绩:
```c++
int score;
char grade;
// 获取用户输入的分数
score = 85; // 示例分数
// 使用switch语句判断等级
switch (score / 10) {
case 10: // 100分
grade = 'A';
break;
case 9: // 90 - 99分
grade = 'B';
break;
case 8: // 80 - 89分
grade = 'B';
break;
case 7: // 70 - 79分
grade = 'C';
break;
case 6: // 60 - 69分
grade = 'D';
break;
default: // 其他分数
grade = 'E';
break;
}
// 输出结果
printf("百分制成绩 %d 分对应的等级是: %c\n", score, grade);
```
在这个例子中,我们首先获取用户的分数,然后通过`switch`根据分数段分配相应的字母等级。当`score`落在某一段时,就执行对应分支的代码并跳出`switch`。如果分数不在已定义的范围内,就会执行`default`分支。
阅读全文
相关推荐


















