能不能拓展上面的结构体并在主函数中应用
时间: 2023-08-14 20:04:40 浏览: 72
当然可以!我可以为你扩展这个结构体,并在主函数中应用它。以下是一个示例:
C++
#include <iostream>
using namespace std;
struct ShoppingRack {
int rackNumber; // 购物架编号
char category[20]; // 商品类别
int numOfItems; // 商品数量
float priceOfItem; // 商品单价
float totalPrice; // 该购物架总价
};
int main() {
ShoppingRack sr1, sr2;
sr1.rackNumber = 1;
strcpy(sr1.category, "水果");
sr1.numOfItems = 50;
sr1.priceOfItem = 3.5;
sr1.totalPrice = sr1.numOfItems * sr1.priceOfItem;
sr2.rackNumber = 2;
strcpy(sr2.category, "蔬菜");
sr2.numOfItems = 30;
sr2.priceOfItem = 2.5;
sr2.totalPrice = sr2.numOfItems * sr2.priceOfItem;
cout << "购物架1:" << endl;
cout << "编号:" << sr1.rackNumber << endl;
cout << "商品类别:" << sr1.category << endl;
cout << "商品数量:" << sr1.numOfItems << endl;
cout << "商品单价:" << sr1.priceOfItem << endl;
cout << "该购物架总价:" << sr1.totalPrice << endl;
cout << "购物架2:" << endl;
cout << "编号:" << sr2.rackNumber << endl;
cout << "商品类别:" << sr2.category << endl;
cout << "商品数量:" << sr2.numOfItems << endl;
cout << "商品单价:" << sr2.priceOfItem << endl;
cout << "该购物架总价:" << sr2.totalPrice << endl;
return 0;
}
```
在上面的示例中,我扩展了原来的结构体,增加了一个成员变量totalPrice,用来表示该购物架的总价。在主函数中,我创建了两个ShoppingRack对象,分别代表两个购物架。我给这两个对象的成员变量赋值,并计算了每个购物架的总价。最后,我输出了每个购物架的信息,包括编号、商品类别、商品数量、商品单价和总价。
阅读全文