有一个售货柜员机,内有多种商品供人购买(商品种类不超过100个),每种商品有 名称、数量、价等信息。编程完成n种商品信息的输入输出。 注意:输入时,第一行输入商品种类个数n,第二行依次输入商品的名称,数量,单价。 输出时,输出商品名称、数量、单价(保留1位小数)和总价(等于单价*数量,保留2位小 数),不同数字之间有一个空格。 用C语言
时间: 2023-12-03 14:45:44 浏览: 77
以下是一个示例代码,实现了商品信息的输入和输出:
```c
#include <stdio.h>
#include <string.h>
#define MAX_ITEMS 100
struct item {
char name[20];
int quantity;
float price;
};
int main() {
int n;
struct item items[MAX_ITEMS];
// 输入商品种类个数
scanf("%d", &n);
// 输入商品信息
for (int i = 0; i < n; i++) {
scanf("%s %d %f", items[i].name, &items[i].quantity, &items[i].price);
}
// 输出商品信息
for (int i = 0; i < n; i++) {
printf("%s %d %.1f %.2f\n", items[i].name, items[i].quantity, items[i].price, items[i].quantity * items[i].price);
}
return 0;
}
```
注意,这个代码假设商品名称最长为20个字符,如果需要支持更长的商品名称,可以将`name`字段改为动态分配的字符数组。此外,如果输入不符合格式要求,这个代码无法正确处理。在实际应用中,需要进行输入格式检查和错误处理。
相关推荐
![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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)