c编写程序在屏幕上显示计算运费表(如下图所示),用户根据提示选择城市与货物重量,输出如下图所示的运行结果
时间: 2024-02-23 17:58:26 浏览: 30
以下是一个使用 C 语言编写的程序,用于计算货运费用并输出运费表:
```c
#include <stdio.h>
int main() {
int city, weight;
float price;
printf("请选择城市:\n");
printf("1. 北京\n");
printf("2. 上海\n");
printf("3. 广州\n");
printf("4. 深圳\n");
scanf("%d", &city);
printf("请输入货物重量(kg):");
scanf("%d", &weight);
switch (city) {
case 1:
if (weight <= 10) {
price = 28.0;
} else if (weight <= 20) {
price = 38.0;
} else if (weight <= 30) {
price = 48.0;
} else {
price = 58.0;
}
break;
case 2:
if (weight <= 10) {
price = 30.0;
} else if (weight <= 20) {
price = 40.0;
} else if (weight <= 30) {
price = 50.0;
} else {
price = 60.0;
}
break;
case 3:
if (weight <= 10) {
price = 32.0;
} else if (weight <= 20) {
price = 42.0;
} else if (weight <= 30) {
price = 52.0;
} else {
price = 62.0;
}
break;
case 4:
if (weight <= 10) {
price = 34.0;
} else if (weight <= 20) {
price = 44.0;
} else if (weight <= 30) {
price = 54.0;
} else {
price = 64.0;
}
break;
default:
printf("输入的城市不正确!\n");
return 0;
}
printf("\n");
printf("城市:%s\n", city == 1 ? "北京" : city == 2 ? "上海" : city == 3 ? "广州" : "深圳");
printf("货物重量:%d kg\n", weight);
printf("运费:%g 元\n", price);
return 0;
}
```
在上面的程序中,根据用户的选择和输入,使用 `switch` 语句计算出对应的运费,并输出运费表。需要注意的是,程序中使用了嵌套的三目运算符来输出城市名称,这是一种简洁的写法,但也可以使用 `if` 语句等其他方式来实现。