用C语言写一个仓库管理系统,并注释
时间: 2023-12-29 10:19:18 浏览: 147
好的,以下是一个简单的仓库管理系统的C语言代码,并附有注释说明:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_ITEMS 100 // 仓库最大存储物品数量
#define ITEM_NAME_LEN 20 // 物品名称的最大长度
// 物品结构体
typedef struct {
char name[ITEM_NAME_LEN];
int quantity;
float price;
} Item;
// 仓库结构体
typedef struct {
Item items[MAX_ITEMS]; // 物品数组
int num_items; // 当前存储的物品数量
} Warehouse;
// 添加物品到仓库
void add_item(Warehouse *warehouse, char *name, int quantity, float price) {
if (warehouse->num_items >= MAX_ITEMS) {
printf("仓库已满,无法添加物品!\n");
return;
}
Item item;
strncpy(item.name, name, ITEM_NAME_LEN); // 复制物品名称到item结构体内
item.quantity = quantity;
item.price = price;
warehouse->items[warehouse->num_items++] = item; // 添加物品到仓库中
printf("物品已成功添加到仓库!\n");
}
// 从仓库中删除指定物品
void remove_item(Warehouse *warehouse, char *name) {
int i, j, found = 0;
for (i = 0; i < warehouse->num_items; i++) {
if (strcmp(warehouse->items[i].name, name) == 0) {
found = 1;
break;
}
}
if (!found) {
printf("未找到要删除的物品!\n");
return;
}
for (j = i; j < warehouse->num_items - 1; j++) {
warehouse->items[j] = warehouse->items[j + 1]; // 将物品数组前移
}
warehouse->num_items--;
printf("物品已成功从仓库中删除!\n");
}
// 显示仓库中所有物品
void show_items(Warehouse *warehouse) {
if (warehouse->num_items == 0) {
printf("仓库为空,暂无物品!\n");
return;
}
printf("仓库中共有%d件物品:\n", warehouse->num_items);
int i;
for (i = 0; i < warehouse->num_items; i++) {
printf("名称:%s,数量:%d,单价:%.2f元\n", warehouse->items[i].name, warehouse->items[i].quantity, warehouse->items[i].price);
}
}
int main() {
Warehouse warehouse = {0}; // 初始化仓库
int choice;
char name[ITEM_NAME_LEN];
int quantity;
float price;
while (1) {
printf("请选择操作:\n");
printf("1. 添加物品\n");
printf("2. 删除物品\n");
printf("3. 显示物品列表\n");
printf("4. 退出\n");
scanf("%d", &choice);
switch (choice) {
case 1:
printf("请输入物品名称:");
scanf("%s", name);
printf("请输入物品数量:");
scanf("%d", &quantity);
printf("请输入物品单价:");
scanf("%f", &price);
add_item(&warehouse, name, quantity, price); // 调用添加物品函数
break;
case 2:
printf("请输入要删除的物品名称:");
scanf("%s", name);
remove_item(&warehouse, name); // 调用删除物品函数
break;
case 3:
show_items(&warehouse); // 调用显示物品函数
break;
case 4:
printf("感谢使用本系统!\n");
exit(0);
default:
printf("无效的选择,请重新输入!\n");
break;
}
}
return 0;
}
```
以上代码实现了一个简单的仓库管理系统。注释已放在代码中,方便您理解。
阅读全文