我可以帮您写一篇关于超市收费程序的C语言模拟文章。下面是一个简单但完整的示例,其中包括创建商品、添加购物车、计算总价和支付等功能。
---
超市收费程序模拟
在这个例子中,我们将用C语言编写一个简单的超市收费程序。程序将允许用户添加商品到购物车,查看购物车中的商品和总价,以及完成支付操作。
代码示例
```c
include
include
// 定义商品结构体
typedef struct {
int id;
char name[50];
float price;
} Product;
// 定义购物车结构体
typedef struct {
Product products;
int count;
} ShoppingCart;
// 函数声明
void addProduct(ShoppingCart cart, Product product);
void viewCart(ShoppingCart cart);
float calculateTotal(ShoppingCart cart);
void checkout(ShoppingCart cart);
int main() {
ShoppingCart cart = {NULL, 0};
Product products[] = {
{1, "苹果", 3.5},
{2, "香蕉", 2.0},
{3, "橘子", 4.0},
{4, "牛奶", 10.0}
};
int n = sizeof(products) / sizeof(products[0]);
int choice;
while (1) {
printf(" 欢迎来到超市收费系统 ");
printf("1. 添加商品 ");
printf("2. 查看购物车 ");
printf("3. 完成支付 ");
printf("4. 退出 ");
printf("请选择操作: ");
scanf("%d", &choice);
getchar(); // 清除缓冲区中的换行符
switch (choice) {
case 1: {
int id, quantity;
printf("请输入商品ID和数量: ");
scanf("%d %d", &id, &quantity);
getchar(); // 清除缓冲区中的换行符
for (int i = 0; i < n; i++) {
if (products[i].id == id) {
addProduct(&cart, (Product){id, products[i].name, products[i].price});
break;
}
}
break;
}
case 2: {
viewCart(cart);
break;
}
case 3: {
checkout(&cart);
break;
}
case 4: {
exit(0); // 退出程序
}
default: {
printf("无效选择,请重新选择。 ");
}
}
}
return 0;
}
```