Visions23
Visions23

Reputation: 85

first rand() generates the same value after srand(time(0))

srand(time(0)) does not seem to be seeding rand() correctly, the 1st number generated is always the same.

This is running on OS X, is there something wrong with my settings or my code? I do wait a couple of seconds to rerun the program. The 1st number increments only a day later, the rest of the numbers are always random.

#include<iostream>
using namespace std;

int main ()
{
    int Num1,Num2;

    // seed the random number generator

    srand((unsigned int )time(NULL));

    Num1 = rand() %49 +1 ;

    do {Num2 = rand() % 49 + 1;}
    while(Num2 == Num1);

    ///Display Random Numbers

    cout<<"Numbers are: "<<endl;
    cout<<Num1<<" "<<Num2<<endl<<endl;

    return 0;
}

Upvotes: 4

Views: 1462

Answers (3)

Visions23
Visions23

Reputation: 85

Besides using sranddev() instead of rand(). Increasing the range also form %49 to 50 or higher also seemed to work.

Upvotes: 0

Variable Length Coder
Variable Length Coder

Reputation: 8116

You are getting the same numbers because the seeds are so close in value and the random generator hasn't had time to diverge yet. On OS X use sranddev() instead of srand(), it will give you a better seed and avoid this problem.

#include<iostream>
using namespace std;

int main()
{
  int a, b;

  // seed the random number generator
  sranddev();

  a = rand();
  b = rand();

  cout << a << " " << (a % 49) + 1 << endl
       << b << " " << (b % 49) + 1 << endl << endl;

  return 0;
}

Upvotes: 3

Retired Ninja
Retired Ninja

Reputation: 4924

Assuming you have access to C++11, you would have better luck with something like this:

#include <iostream>
#include <random>

int main()
{
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_int_distribution<> dis(1, 50);
    std::cout << "Numbers are: " << dis(gen) << " " << dis(gen) << "\n";
    return 0;
}

rand is typically a pretty poor random generator with limited range of values and using % N to limit the values makes it even worse. There's a presentation about why rand isn't a good choice here: http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful

Upvotes: 0

Related Questions