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