#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// 定义商品结构体
typedef struct {
char name[50];
float price;
int quantity;
} Product;
// 显示菜单
void showMenu() {
printf(“1. 商品入库\n”);
printf(“2. 商品销售\n”);
printf(“3. 查看库存\n”);
printf(“4. 退出\n”);
}
// 商品入库
void addProduct(Product *products, int *numProducts) {
Product newProduct;
printf(“请输入商品名称: “);
scanf(”%s”, newProduct.name);
printf(“请输入商品价格: “);
scanf(”%f”, &newProduct.price);
printf(“请输入商品数量: “);
scanf(”%d”, &newProduct.quantity);
products[*numProducts] = newProduct;
(*numProducts)++;
}
// 商品销售
void sellProduct(Product *products, int numProducts) {
int choice;
printf(“请选择要销售的商品编号: “);
scanf(”%d”, &choice);
if (choice >= 1 && choice <= numProducts) {
int quantityToSell;
printf("请输入要销售的数量: ");
scanf("%d", &quantityToSell);
if (quantityToSell <= products[choice - 1].quantity) {
products[choice - 1].quantity -= quantityToSell;
printf("销售成功!\n");
} else {
printf("库存不足,销售失败!\n");
}
} else {
printf("无效的选择!\n");
}
}
// 查看库存
void viewInventory(Product *products, int numProducts) {
printf(“库存列表:\n”);
for (int i = 0; i < numProducts; i++) {
printf("%d. %s - 价格: %.2f - 数量: %d\n", i + 1, products[i].name, products[i].price, products[i].quantity);
}
}
int main() {
Product products[100]; // 假设最多存储 100 种商品
int numProducts = 0;
int choice;
do {
showMenu();
printf("请选择操作: ");
scanf("%d", &choice);
switch (choice) {
case 1:
addProduct(products, &numProducts);
break;
case 2:
sellProduct(products, numProducts);
break;
case 3:
viewInventory(products, numProducts);
break;
case 4:
printf("退出程序\n");
break;
default:
printf("无效的选择,请重新输入\n");
}
} while (choice!= 4);
return 0;
}