user2151985
user2151985

Reputation:

C++ for loop not waiting to finish?

I'm having some trouble with this code:

for (long long int loop = 0; loop < 50000000; loop++)
{
    srand( (unsigned)time(NULL) ); // set the seed
    int r = abs(rand()); // stores the random seed for this loop
    int res = loop + r - r * r / r; // random operations with the loop number and the random seed.
    cout << "Loop number: " << loop << ". " << "Result: ";
    cout << res << endl;
}//this was missing

If you run that code, you can see, very clearly in the console, that the output of it is only doing the calculations once every few seconds. What's going on? The number should be completely different for each loop, because it's doing calculations with random numbers. Instead, the number changes every x loops ran, and then it only seems to increase between these times it actually does the math.

Do I need to specify I want the loop to wait until everything is complete before moving on?

Upvotes: 0

Views: 482

Answers (2)

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133014

Because you're doing srand in the loop with time seed. time()'s granularity is in seconds so until one second has passed it will return the same seed and therefore the same random number. Do srand outside the loop.

The point of seeding the rand function with srand is that the sequence of generated random numbers is different with each program run. You need only one srand in your program.

And by the way, rand() always returns a non-negative number, so abs is useless. Be careful though that r can be 0, and you do divide by r, which potentially has undefined behavior. do r = rand()+1 to be safe.

Upvotes: 12

Agus Arias
Agus Arias

Reputation: 467

Your seed is the same for the same second, so the random numbers with that seed will be the same. You could try taking out the srand.

srand( (unsigned)time(NULL) ); // set the seed
for (long long int loop = 0; loop < 50000000; loop++)
{
    int r = abs(rand()); // stores the random seed for this loop
    int res = loop + r - r * r / r; // random operations with the loop number and the random seed.
    cout << "Loop number: " << loop << ". " << "Result: ";
    cout << res << endl;
}

Cheers

Upvotes: 1

Related Questions