rand() - Same Ten Digits Printed -- Random?

I must be using the rand() function wrong, because every time I run this program, even after recompiling, it prints out the same ten digits:
3675356291


code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <cstdlib>
using namespace 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.
closed account (z05DSL3A)
You need to seed the RNG with srand()
http://www.cplusplus.com/reference/clibrary/cstdlib/srand/
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;

class Random
{
  public:
    int getnumber(); // Retrieve a random number
    static void seed(unsigned int 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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <iostream>
#include <cstdlib>
#include <time.h>
using namespace std;

class Random
{
  public:
    int getnumber(); // Retrieve a random number
private:
    static bool seeded;
};

bool Random::seeded = false;

int Random::getnumber()
{
    if(!seeded)
    {
        srand((unsigned int) 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;
}
Last edited on
Thank you very much.
Topic archived. No new replies allowed.