#include <iostream>
#include <cstdlib>
usingnamespace std;
class Random
{
public:
int getnumber(); // Retrieve a random number
};
int Random::getnumber()
{
int random = rand() % 10;
return random;
}
int main()
{
Random num;
for (int x = 0; x < 10; x += 1)
{
cout << num.getnumber(); // Print a random number
cout.flush(); // Clear output buffer
usleep(100000); // Wait 1/10 sec between numbers
}
cout << endl;
return 0;
}
Why aren't the numbers randomly chosen each time the program is run? The compiler seems to predefine the numbers.
#include <iostream>
#include <cstdlib>
#include <time.h>
usingnamespace std;
class Random
{
public:
int getnumber(); // Retrieve a random number
staticvoid seed(unsignedint seed = time(NULL) )
{
srand (seed);
};
};
int Random::getnumber()
{
int random = rand() % 10;
return random;
}
int main()
{
Random::seed();
Random num;
for (int x = 0; x < 10; x += 1)
{
cout << num.getnumber(); // Print a random number
cout.flush(); // Clear output buffer
}
cout << endl;
return 0;
}
edit:
The following would mean that you would not have to remeber to seed the RNG
#include <iostream>
#include <cstdlib>
#include <time.h>
usingnamespace std;
class Random
{
public:
int getnumber(); // Retrieve a random number
private:
staticbool seeded;
};
bool Random::seeded = false;
int Random::getnumber()
{
if(!seeded)
{
srand((unsignedint) time(NULL) );
seeded = true;
}
int random = rand() % 10;
return random;
}
int main()
{
Random num;
for (int x = 0; x < 10; x += 1)
{
cout << num.getnumber(); // Print a random number
cout.flush(); // Clear output buffer
}
cout << endl;
return 0;
}