让我们来聊聊如何用C语言编写一个超市打折系统。想象一下,你是一家超市的经理,想要为顾客提供不同等级的折扣优惠,比如针对购买超过100元的顾客提供5%的折扣,购买超过200元的顾客享受10%的折扣。我们将逐步构建这样一个系统。
1. 定义数据结构
我们需要一个结构体来保存商品信息。假设我们有两个商品
名称和价格。
```c
include
include
typedef struct {
char name[50];
double price;
} Product;
```
2. 输入商品信息
我们可能需要从用户那里输入商品信息。为了简化,假设我们事先知道商品数量,并输入到数组中。
```c
void inputProducts(Product products[], int count) {
for (int i = 0; i < count; i++) {
printf("输入第%d个商品的名称和价格: ", i + 1);
scanf("%s %lf", products[i].name, &products[i].price);
}
}
```
3. 计算总金额和折扣
我们需要计算每个商品的总金额,并根据折扣规则提供优惠。例如,如果总金额超过100元,提供5%的折扣。如果总金额超过200元,提供10%的折扣。
```c
double calculateTotal(Product products[], int count) {
double total = 0.0;
for (int i = 0; i < count; i++) {
total += products[i].price;
}
return total;
}
double applyDiscount(double total) {
if (total > 200) {
return total 0.9; // 10% discount
} else if (total > 100) {
return total 0.95; // 5% discount
} else {
return total; // no discount
}
}
```
4. 主函数和流程控制
我们整合所有部分到主函数中,让用户输入商品信息,计算总金额并应用折扣。然后输出最终的总金额(包括折扣)。
```c
int main() {
Product products[10]; // 假设最多有10个商品
int count;
printf("请输入商品数量: ");
scanf("%d", &count); // 限制商品数量不超过10个(在数组大小范围内)
inputProducts(products, count); // 输入商品信息到数组
double total = calculateTotal(products, count); // 计算总金额(无折扣)
double discountedTotal = applyDiscount(total); // 应用折扣规则并计算折扣后金额
printf("打折后的总金额是: %.2lf元 ", discountedTotal); // 输出结果(保留两位小数)
return 0; // 程序结束并返回0表示成功运行(在main函数中)
}
```