用switch语句编程实现,键盘输入学生成绩
时间: 2023-05-15 09:07:15 浏览: 94
以下是使用 switch 语句编写的程序,可以输入学生成绩并输出相应的等级:
```c
#include <stdio.h>
int main() {
int score;
printf("请输入学生成绩:");
scanf("%d", &score);
switch (score / 10) {
case 10:
case 9:
printf("成绩等级为:A\n");
break;
case 8:
printf("成绩等级为:B\n");
break;
case 7:
printf("成绩等级为:C\n");
break;
case 6:
printf("成绩等级为:D\n");
break;
default:
printf("成绩等级为:E\n");
break;
}
return 0;
}
```
输入学生成绩后,程序会将其除以 10 并向下取整,然后根据结果进行 switch 分支判断,输出相应的等级。
相关问题
由键盘输入商品的价格和购买的数量,编程计算购买x件商品应付总金额。要求用switch语句编程实现。c语言
以下是用switch语句编写的C语言代码,实现计算购买x件商品应付总金额的功能:
```c
#include <stdio.h>
int main() {
float price, total_price;
int quantity;
printf("请输入商品价格:");
scanf("%f", &price);
printf("请输入购买数量:");
scanf("%d", &quantity);
switch(quantity) {
case 1:
total_price = price;
break;
case 2:
total_price = price * 2 * 0.95;
break;
case 3:
total_price = price * 3 * 0.9;
break;
case 4:
total_price = price * 4 * 0.85;
break;
default:
total_price = price * quantity * 0.8;
break;
}
printf("购买%d件商品应付总金额为%.2f元\n", quantity, total_price);
return 0;
}
```
在这个程序中,我们首先通过键盘输入获取商品价格和购买数量。然后,使用switch语句根据购买数量计算应付总金额。如果购买数量为1,总金额就是商品价格;如果购买数量为2,总金额就是商品价格乘以2再打95折,以此类推。最后,用printf函数输出结果。
由键盘输入商品的价格和购买的数量,编程计算购买x件商品应付总金额。要求用switch语句编程实现。
下面是用 C++ 编写的程序,可以实现您的需求:
```cpp
#include <iostream>
using namespace std;
int main() {
float price; // 商品单价
int quantity; // 商品数量
float total; // 总金额
cout << "请输入商品单价:";
cin >> price;
cout << "请输入购买数量:";
cin >> quantity;
switch (quantity) {
case 1:
total = price;
break;
case 2:
total = price * 2;
break;
case 3:
total = price * 3;
break;
case 4:
total = price * 4;
break;
case 5:
total = price * 5;
break;
default:
total = price * quantity;
break;
}
cout << "应付总金额为:" << total << endl;
return 0;
}
```
程序中,我们先接收用户输入的单价和数量,并且使用 switch 语句根据购买数量来计算总金额。如果购买数量大于 5,我们默认按照 `总金额 = 商品单价 x 购买数量` 的方式来计算。最后将计算出的总金额输出到屏幕上。
注意,在实际的商业场景中,我们需要考虑到更多的因素,比如打折、优惠券等等,这些都需要在程序中进行特殊处理。