有10种商品的数据记录,每个记录包括“商品编号”、 “商品名”、 “单价”、 “数量”。请用结构体数组实现每种商品总价(商品总价=单价×数量)的计算。
时间: 2023-05-31 13:20:04 浏览: 143
### 回答1:
可以定义一个结构体,包含商品编号、商品名、单价和数量四个成员变量。然后定义一个结构体数组,用来存储10种商品的数据记录。遍历结构体数组,计算每种商品的总价,并将结果存储在另一个数组中。最后输出每种商品的总价即可。具体实现可以参考以下代码:
```
#include <stdio.h>
struct Product {
int id; // 商品编号
char name[20]; // 商品名
float price; // 单价
int quantity; // 数量
};
int main() {
struct Product products[10] = {
{1, "商品1", 2.5, 10},
{2, "商品2", 3., 5},
{3, "商品3", 1.5, 20},
{4, "商品4", 4., 8},
{5, "商品5", 2., 15},
{6, "商品6", 3.5, 6},
{7, "商品7", 2., 12},
{8, "商品8", 5., 3},
{9, "商品9", 1., 30},
{10, "商品10", 2., 10}
};
float total[10]; // 存储每种商品的总价
// 计算每种商品的总价
for (int i = ; i < 10; i++) {
total[i] = products[i].price * products[i].quantity;
}
// 输出每种商品的总价
for (int i = ; i < 10; i++) {
printf("商品%d的总价为%.2f元\n", products[i].id, total[i]);
}
return ;
}
```
### 回答2:
题目要求我们使用结构体数组来计算每种商品的总价。所以我们需要先定义一个存储商品信息的结构体,包括商品编号、商品名、单价和数量,代码如下:
```
struct Goods {
int id; // 商品编号
char name[20]; // 商品名
float price; // 单价
int quantity; // 数量
};
```
接下来,我们要定义结构体数组来存储10种商品的数据记录,代码如下:
```
Goods goodsArray[10] = {
{001, "商品1", 10.5, 3},
{002, "商品2", 8.9, 5},
{003, "商品3", 12.3, 2},
{004, "商品4", 6.5, 4},
{005, "商品5", 15.7, 1},
{006, "商品6", 9.8, 7},
{007, "商品7", 14.6, 2},
{008, "商品8", 5.5, 6},
{009, "商品9", 11.2, 3},
{010, "商品10", 7.9, 4},
};
```
其中,每个花括号内的内容分别为商品编号、商品名、单价和数量。
接下来,我们就可以通过循环遍历结构体数组,来计算每种商品的总价并输出。代码如下:
```
float totalPrice[10]; // 存储每种商品的总价
// 计算每种商品的总价
for (int i = 0; i < 10; i++) {
totalPrice[i] = goodsArray[i].price * goodsArray[i].quantity;
}
// 输出每种商品的总价
for (int i = 0; i < 10; i++) {
printf("%s的总价为%.2f元\n", goodsArray[i].name, totalPrice[i]);
}
```
其中,我们定义了一个float类型的数组totalPrice来存储每种商品的总价。第一个循环遍历结构体数组,使用商品单价和数量的乘积来计算每种商品的总价,并将结果存储在totalPrice数组中。第二个循环遍历结构体数组,输出每种商品的总价。
最后,我们可以得到每种商品的总价。
### 回答3:
为了实现每种商品总价的计算,我们可以创建一个包含所有记录的结构体数组。每个记录都包含四个属性:“商品编号”、“商品名”、“单价”和“数量”。
为了计算每种商品的总价,我们可以定义一个函数,该函数首先遍历所有的记录,然后计算每种商品的总价。我们可以用循环语句来遍历所有的记录,并用一个变量来保存每种商品的总价,每次循环都更新变量的值。
以下是示例代码:
```c
#include <stdio.h>
struct Record {
int product_id;
char product_name[50];
double price;
int quantity;
};
int main() {
struct Record records[10] = {
{ 101, "Product 1", 10.5, 3 },
{ 102, "Product 2", 5.7, 2 },
{ 103, "Product 3", 7.2, 4 },
{ 104, "Product 4", 9.8, 1 },
{ 105, "Product 5", 4.3, 5 },
{ 106, "Product 6", 6.1, 2 },
{ 107, "Product 7", 8.5, 3 },
{ 108, "Product 8", 11.2, 2 },
{ 109, "Product 9", 7.4, 5 },
{ 110, "Product 10", 3.9, 3 }
};
double total_prices[10] = {0};
int i;
for (i = 0; i < 10; i++) {
double price = records[i].price;
int quantity = records[i].quantity;
total_prices[i] = price * quantity;
}
for (i = 0; i < 10; i++) {
printf("Product %d, %s: Total price = %.2lf\n",
records[i].product_id, records[i].product_name, total_prices[i]);
}
return 0;
}
```
在这个示例中,我们创建了一个包含10个记录的结构体数组。然后,我们定义了一个名为“total_prices”的数组来存储每种商品的总价。接下来,我们通过一个循环遍历所有的记录,并计算每种商品的总价。我们将每种商品的总价存储在“total_prices”数组中。 最后,我们再次遍历所有的记录,并使用printf语句打印每种商品的总价。