Answer the question
In order to leave comments, you need to log in
How to create a method so that it sets random properties to an object?
There is a program that has a class that has a method that should set random parameters to an object of the class, but when this method is applied to two different objects of the class, the result is the same. How can I modify the program so that each time this method is applied to an object, a different result is obtained?
#include <iostream>
#include <ctime>
using namespace std;
enum Level {easy=1, hard, medium};
class alpha
{
private:
Level level;
int number;
public:
alpha() : level(easy), number(5)
{}
void gen()
{
srand(time(NULL));
number = rand() % 10 + 1;
int levelgen = rand() % 3 + 1;
switch (levelgen)
{
case 1:
level = easy;
break;
case 2:
level = medium;
case 3:
level = hard;
default:
break;
}
}
void disp()
{
if (level == hard)
cout << "level - ???? " << endl;
else
{
cout << "level = ";
switch (level)
{
case easy:
cout << "easy" << endl;
break;
case medium:
cout << "medium" << endl;
break;
default:
break;
}
}
cout << "number = " << number << endl;
}
};
int main()
{
srand(time(NULL));
alpha obj1;
obj1.gen();
obj1.disp();
alpha obj2;
obj2.gen();
obj1.disp();
system("pause");
}
Answer the question
In order to leave comments, you need to log in
srand(time(NULL));
Should be at the beginning of the program, although it is better to use a normal PRNG. And the problem is that you are displaying the data of the same object:
alpha obj1;
obj1.gen();
obj1.disp();
alpha obj2;
obj2.gen();
obj1.disp();
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question