如何使用三个参数化构造函数的rand()函数初始化对象的数组
How can i initialize array of object with rand() function of a three parameterized constructor?
这是一个程序,可从数组中找到最大和最小的盒子。如何自动生成一个随机数并将其存储在数组中?
如何自动生成长度,宽度和高度并将其存储在对象的数组中?
#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() = default;
相关文章:
- C++使用 rand 定义函数语法
- rand()函数在特定问题中的工作
- 如何生成比用户使用 rand() 函数输入的数字大 5-10% 的数字?
- rand()/RAND_MAX 函数每次打印 1
- 在C++中使用 rand() 函数的替代方案
- 如何使用三个参数化构造函数的rand()函数初始化对象的数组
- 为什么循环只在 c++ 中使用 rand() 函数时才运行 1 或 2 次
- rand() 函数通过升序到前一个数字来生成下一个数字
- 如何在 rand() 函数中使用枚举值
- 我想用rand和函数生成一些数学问题
- Rand() 在每次函数调用时返回相同的值
- 如何调用一个变量(包含rand()函数)并得到不同的数字
- rand()在通过函数调用时生成相同的随机数集(即使在使用srand(time(NULL)进行种子设定之后)
- 胎面 1 错误 - 使用 rand() 函数
- 在 C++ 中编写多个 if-else 语句并使用 rand() 函数进行分支
- 如何使用 rand() 函数每次都提出不同的问题
- 带有 rand() 函数的动态链接器错误
- 用于 c++ 中函数 rand() 的公式
- rand() 和 random() 函数有什么区别
- rand() 函数没有生成足够的随机