tags:

views:

204

answers:

5

Why are my C++ numbers not random?

#include <iostream>
#include <cstdlib>
using namespace std;


int main()
{
    int randomNumber = rand() % 100;


    for (randomNumber = 0; randomNumber < 20; randomNumber++)
    {

        cout << randomNumber << endl;
    }
    return 0;
}

//Why are my 20 numbers not random?
+3  A: 

You're assigning randomNumber a random value, and then overwriting it with the numbers 0 through 19 in your for loop. Before your loop, you have a random number.

Wooble
+1  A: 

You need to use time() function as a seed in srand() and then use rand().

srand(time(NULL));

By the way you are not printing the rand() result, use this after the srand call:

for (int i= 0; i < 20; i++)
{
    int randomNumber = rand() % 100;
    cout << randomNumber << endl;
}
Alex LE
+2  A: 

You need to call rand() each time you want a random number. As you have it now you're generating one random number, then incrementing it and printing it out 20 times so you're going to get 20 sequential numbers.

Try something like

srand(time(NULL)); // Seeding the random number generator

for(int i=0; i<20; ++i)
{
    cout << (rand() % 100) << endl;
}

The seeding of the random number generator is important, without that you would generate the same numbers every time you ran the program.

Graphics Noob
Note that it is generally not advised to simply use modulus to get a random number in the desired range.
Trent
@Trent: please, do go on...
Graphics Noob
@Graphics Noob, this is probably a topic better saved for another SO question, but... The argument is that the results of using modulus are not uniformly distributed. Here are two references: http://stackoverflow.com/questions/288739/generate-random-numbers-uniformly-over-entire-range and http://www.cplusplus.com/reference/clibrary/cstdlib/rand/
Trent
A: 
#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
    for (int i = 0; i < 20; i++)
    {
        int randomnumber = rand() % 100;
        cout << randomNumber << endl;
    }
    return 0;
}

P.S. I hope this is a joke :(

Kaleb Brasee
+3  A: 

You need to properly seed your random number generator, and then you need to repeatedly call rand() to get a new random number.

For example:

srand(time(NULL));
for (int randomNumber = 0; randomNumber < 20; randomNumber++) 
{ 

    cout << (rand() % 100) << endl; 
} 
Michael