我还是新上课,所以我到目前为止所做的一切。在这个程序中,我必须提示用户输入多少产品和价格,我必须再次显示如下:
No Product Code Price
1 101 4.50
并计算平均价格。
我的班级必须容纳100个对象,我仍然不确定如何实施。希望有人能帮助我。
#include <iostream>
using namespace std;
class Product{
private :
int code;
double price;
public :
Product ();
void setCode(int);
void setPrice(double);
int getCode();
double getPrice();
};
Product :: Product()
{
code = 0;
price = 0;
}
void Product :: setCode(int c)
{
code = c;
}
void Product :: setPrice(double p)
{
price = p;
}
int Product :: getCode()
{
return code;
}
double Product :: getPrice()
{
return price;
}
int main(){
const int size = 100;
Product m[size];
int procode;
double proprice;
int num;
double sum= 0;
cout << "How many products to enter? ";
cin >> num;
cout << endl;
for(int i=0; i<num ;i++)
{
cout << "Enter the information of product #"<< (i+1)<<endl;
int code;
cout << "\tProduct Code: ";
cin >> code;
m[i].setCode( code );
double price;
cout << "\tPrice: ";
cin >> price;
m[i].setPrice( price );
sum = sum + price;
}
///output??
cout <<"No"<<" "<<"Product Code"<<" "<<"Price" <<endl;
cout<<" "<<m[i].getCode()<<" "<<m[i].getPrice()<<endl;
cout<<"Average: " << sum/num << endl;
return 0;
}
答案 0 :(得分:1)
for(int i=0; i<num ;i++)
{
cout << "Enter the information of product #"<< (i+1)<<endl;
cout << "Product Code:";
cin >> procode;
m[i].setCode(procode);
cout < "\nPrice:";
cin >> proprice;
m[i].setPrice(proprice);
}
这将设置所需的对象数。
以
方式访问 cout<<m[index].getCode()<<m[index].getPrice();
答案 1 :(得分:1)
您的意思是动态分配吗?
如果您希望用户指定可变数量的产品,则必须在知道num
后动态创建数组。
例如:
int main() {
Product * m;
int num;
cout << "How many products to enter? ";
cin >> num;
cout << endl;
m = new Product[num];
for (int i=0; i<num; i++) {
// something with the array
}
delete [] m;
return 0;
}
答案 2 :(得分:0)
函数main可以按以下方式编写
int main()
{
const size_t MAX_ITEMS = 100;
Product m[MAX_ITEMS];
size_t num;
cout << "How many products to enter? ";
cin >> num;
if ( MAX_ITEMS < num ) num = MAX_ITEMS;
for ( size_t i = 0; i < num; i++ )
{
cout << "\nEnter the information of product #" << (i+1) << endl;
int code;
cout << "\tProduct Code: ";
cin >> code;
m[i].setCode( code );
double price;
cout < "\tPrice: ";
cin >> price;
m[i].setPrice( price );
}
// here can be the code for output data
return 0;
}