如何用C语言编写一个简单的运费计算程序,轻松计算不同重量商品的运费

2026-10-20 0 阅读

当你需要快速计算不同重量商品的运费时,一个用C语言编写的简单程序可以帮你节省时间和精力。以下是一个基础的运费计算程序的示例,它将根据重量和固定的费率来计算运费。

程序设计思路

  1. 确定费率:首先,你需要设定不同的重量区间和对应的费率。
  2. 输入重量:用户输入商品的重量。
  3. 计算运费:根据输入的重量和预定的费率区间,计算运费。
  4. 输出结果:显示计算出的运费。

代码实现

#include <stdio.h>

// 定义一个结构体来存储费率区间和费率
typedef struct {
    float min_weight; // 最小重量
    float max_weight; // 最大重量
    float rate;       // 费率
} Rate;

// 函数声明
float calculate_shipping_cost(float weight, Rate rates[], int num_rates);

int main() {
    // 定义费率数组
    Rate rates[] = {
        {0, 5, 1.5}, // 0到5公斤,费率为1.5元/公斤
        {5, 10, 3.0}, // 5到10公斤,费率为3.0元/公斤
        {10, 100, 4.5} // 10到100公斤,费率为4.5元/公斤
    };
    int num_rates = sizeof(rates) / sizeof(rates[0]); // 费率数量

    float weight;
    printf("请输入商品重量(公斤):");
    scanf("%f", &weight);

    // 计算运费
    float shipping_cost = calculate_shipping_cost(weight, rates, num_rates);

    // 输出结果
    printf("商品的运费为:%.2f元\n", shipping_cost);

    return 0;
}

// 根据重量和费率数组计算运费
float calculate_shipping_cost(float weight, Rate rates[], int num_rates) {
    float cost = 0.0;

    for (int i = 0; i < num_rates; i++) {
        if (weight <= rates[i].max_weight) {
            if (weight < rates[i].min_weight) {
                // 如果重量小于最小重量,则使用最小重量的费率
                cost = rates[i].min_weight * rates[i].rate;
            } else {
                // 如果重量在区间内,则使用当前区间的费率
                cost = (weight - rates[i].min_weight) * rates[i].rate;
            }
            break;
        }
    }

    return cost;
}

程序说明

  • 我们定义了一个Rate结构体来存储费率区间和费率。
  • calculate_shipping_cost函数负责根据重量和费率数组计算运费。
  • 在main函数中,我们首先定义了费率数组,然后提示用户输入重量,接着调用calculate_shipping_cost函数计算运费,并输出结果。

这个程序是一个简单的例子,可以根据实际需求进行调整和扩展,比如增加新的费率区间、处理不同货币单位、或者添加用户界面等。

分享到: