[英]How can i initialize array of object with rand() function of a three parameterized constructor?
這是一個從數組中查找最大和最小Box的程序。 如何自動生成隨機數並將其存儲在數組中?
如何自動生成長度,寬度和高度並將其存儲在對象數組中?
#include <iostream>
#include <stdlib.h>
using namespace std;
class Box{
private:
double length;
double height;
double width;
//parameterized constructor for the Box class to initialized length, height and width
public:
Box(double ilength,double iheight,double iwidth){
length=ilength;
height=iheight;
width=iwidth;
}
//calculate the volume
double getvolume(){
return length*height*width;
}
//calculate the width
double getarea(){
return 2*width*length+2*length*height+2*height*width;
}
};
int main()
{
//Generate the value of length, height and width of every box
double e=(rand()%6)+1;
double f=(rand()%6)+1;
double g=(rand()%6)+1;
double i=(rand()%7)+1;
double j=(rand()%8)+1;
double k=(rand()%9)+1;
double l=(rand()%10)+1;
double m=(rand()%11)+1;
double n=(rand()%12)+1;
cout<<e<<"this is e"<<endl;
cout<<f<<"this is f"<<endl;
cout<<g<<"this is g"<<endl;
cout<<i<<"this is i"<<endl;
cout<<j<<"this is j"<<endl;
cout<<k<<"this is k"<<endl;
cout<<l<<"this is l"<<endl;
cout<<m<<"this is m"<<endl;
cout<<n<<"this is n"<<endl;
Box b[3]={Box(e,f,g),Box(i,j,k),Box(l,m,n)};
double c,d,h,a;
c=b[1].getvolume();
d=b[1].getarea();
h=b[0].getvolume();
a=b[0].getarea();
cout << c <<endl;
cout<< d<<endl;
return 0;
}
這可行,但是還有其他更好的方法嗎?
如果所有盒子的模量值都可以相同,我將執行以下操作:
#include <algorithm>
Box b[3];
std::generate(std::begin(b), std::end(b), []()mutable{return Box(rand()%6+1, rand()%7+1, rand()%8+1);});
您需要向Box類添加默認構造函數:
Box() = default;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.