帮我用C语言写一个商品销售系统
时间: 2023-12-31 08:05:38 浏览: 26
好的,下面是一个简单的商品销售系统的 C 语言代码示例:
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_PRODUCTS 100 // 最多商品数
typedef struct {
char name[20]; // 商品名称
int quantity; // 商品数量
float price; // 商品单价
} Product;
Product products[MAX_PRODUCTS]; // 商品数组
int numProducts = 0; // 当前商品数
// 添加商品
void addProduct(char *name, int quantity, float price) {
if (numProducts < MAX_PRODUCTS) {
strcpy(products[numProducts].name, name);
products[numProducts].quantity = quantity;
products[numProducts].price = price;
numProducts++;
}
}
// 显示所有商品
void showProducts() {
printf("商品列表:\n");
for (int i = 0; i < numProducts; i++) {
printf("%d. %s\t%d\t%.2f\n", i+1, products[i].name, products[i].quantity, products[i].price);
}
}
// 购买商品
void buyProduct(int index, int quantity) {
if (index >= 0 && index < numProducts) {
if (products[index].quantity >= quantity) {
float totalPrice = products[index].price * quantity;
printf("购买成功!%s x%d,共 %.2f 元。\n", products[index].name, quantity, totalPrice);
products[index].quantity -= quantity;
} else {
printf("库存不足!\n");
}
} else {
printf("无效的商品编号!\n");
}
}
int main() {
// 添加一些商品
addProduct("商品1", 10, 9.99);
addProduct("商品2", 5, 19.99);
addProduct("商品3", 20, 4.99);
// 显示商品列表
showProducts();
// 购买商品
int index, quantity;
printf("请输入要购买的商品编号和数量(用空格分隔):");
scanf("%d %d", &index, &quantity);
buyProduct(index-1, quantity);
return 0;
}
```
这个系统包括添加商品、显示商品列表、购买商品三个功能,可以根据需求进行修改和扩展。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)