在超市的收银台,我们经常见到这样一幕
收银员扫描商品条形码,然后机器显示商品价格和总价,最后结算时通过电子支付或现金完成交易。如果我们用C语言来模拟这个过程,可以学到很多编程的知识和技巧。
我们需要创建一个结构体(`struct`)来存储商品的信息,比如商品名称、价格和数量。为了简化,我们设定商品只有一个数量(假设每个商品都是一件)。
```c
include
include
typedef struct {
char name[50];
double price;
int quantity;
} Product;
```
接着,我们可以写一个函数来添加商品到购物车中
```c
void addProduct(Product cart, const char name, double price, int quantity) {
strcpy(cart->name, name);
cart->price = price;
cart->quantity = quantity;
}
```
我们需要一个函数来计算总价
```c
double calculateTotal(Product product) {
return product->price product->quantity;
}
```
我们可以创建一个简单的“超市”主程序来展示如何使用这些功能:
```c
int main() {
Product cart[100]; // 假设购物车最多可以放100个商品
int count = 0; // 当前购物车中的商品数量
addProduct(&cart[count], "苹果", 3.5, 5);
count++; // 添加一个商品后,计数器增加
addProduct(&cart[count], "香蕉", 2.0, 3);
count++; // 再添加一个商品,计数器再次增加
for (int i = 0; i < count; i++) {
printf("商品 %d: %s, 单价: %.2f, 数量: %d, 总价: %.2f ", i+1, cart[i].name, cart[i].price, cart[i].quantity, calculateTotal(&cart[i]));
}
double total = 0.0; // 所有商品的总价
for (int i = 0; i < count; i++) {
total += calculateTotal(&cart[i]); // 计算所有商品的总价
}
printf("所有商品的总价: %.2f ", total);
return 0; // 程序结束
}
```
这个简单的程序模拟了超市的购物过程,包括添加商品到购物车、计算单个商品的总价以及计算所有商品的总价。真实世界的超市收费系统会更加复杂,比如需要处理多个购物车、优惠活动、电子支付接口等。但通过这个模拟,我们可以掌握C语言的基本概念和操作,为后续的学习打下基础。