现有某商店仓库,按不同的入库时间输入了商品名称、入库数量、商品单价, 现在要求输入对应的商品名称,显示该商品的当前仓库内的总数量和平均单价 如果该商品不存在,显示not found。使用C语言编程
时间: 2024-05-15 14:18:57 浏览: 11
好的,我会遵守您的要求。以下是针对您的问题的代码示例,帮助您实现所需的功能。
```
#include <stdio.h>
#include <string.h>
#define MAX_PRODUCTS 100
// 商品结构体
typedef struct {
char name[50]; // 商品名称
int quantity; // 入库数量
float price; // 商品单价
} product;
// 仓库结构体
typedef struct {
product products[MAX_PRODUCTS]; // 商品数组
int count; // 商品数量
} warehouse;
// 根据商品名称在仓库中查找商品,返回该商品在仓库中的下标,如果找不到就返回-1
int find_product_index(warehouse *wh, char *name) {
for (int i = 0; i < wh->count; i++) {
if (strcmp(wh->products[i].name, name) == 0) {
return i;
}
}
return -1; // 找不到商品,返回-1
}
// 添加商品到仓库
void add_product(warehouse *wh, product p) {
// 如果仓库中已经有该商品,就更新该商品的入库数量和商品单价
int index = find_product_index(wh, p.name);
if (index >= 0) {
wh->products[index].quantity += p.quantity;
wh->products[index].price = (wh->products[index].price + p.price) / 2;
// 否则就添加新的商品
} else {
wh->products[wh->count] = p;
wh->count++;
}
}
// 显示商品的当前仓库内的总数量和平均单价
void display_product_info(warehouse *wh, char *name) {
int index = find_product_index(wh, name);
if (index < 0) {
printf("not found\n");
return;
}
printf("total quantity: %d\n", wh->products[index].quantity);
printf("average price: %.2f\n", wh->products[index].price);
}
int main() {
warehouse wh = {0};
// 添加一些商品到仓库中
add_product(&wh, (product){"apple", 10, 3.5});
add_product(&wh, (product){"orange", 20, 2.8});
add_product(&wh, (product){"banana", 30, 1.5});
// 显示商品的信息
display_product_info(&wh, "banana");
display_product_info(&wh, "apple");
display_product_info(&wh, "watermelon");
return 0;
}
```
代码中定义了两个结构体:`product`和`warehouse`,分别代表商品和仓库。`product`结构体包含商品的名称、入库数量和单价,`warehouse`结构体包含商品数组和商品数量。使用`find_product_index`函数可以根据商品名称在仓库中查找商品,返回该商品在仓库中的下标,如果找不到就返回-1。使用`add_product`函数可以将商品添加到仓库中,如果仓库中已经有该商品,就更新该商品的入库数量和商品单价,否则就添加新的商品。最后使用`display_product_info`函数可以根据商品名称显示商品的当前仓库内的总数量和平均单价,如果该商品不存在,就显示"Not found"。
相关推荐
![](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)