Random Number Generator

Aug 2, 2011 at 3:02am
When running the following code block, I need the loop to produce eight different results, but I'm only getting the same result eight times over.

1
2
3
4
5
6
7
8
9
10
 
    unsigned int seed;
    cout << "Enter a seed for random number generation: ";
    cin >> seed;
    srand(seed);
    randValue = (1 + ((rand() + time(0)) % 5));

    for (int i = 0; i < 8; i++) {
    cout << randValue << endl;
	}


If I insert the randValue's formula in the loop, I (of course) get eight different answers. How can I adjust it to where randValue actually produces a different answer when called?
Aug 2, 2011 at 3:09am
You could make randValue a function. Otherwise, it's just a variable and when set, stays at the value you set it.
Aug 2, 2011 at 3:14am
I've made this mistake before.
What happens is although randValue is random initially, the value of that variable doesn't change through each iteration of the loop. try:
1
2
3
4
5
for(int i=0;i<8;i++)
{
    cout << randValue << endl;
    randValue = (1 + ((rand() + time(0)) % 5));
}


Should work :)
Aug 2, 2011 at 3:19am
Thank you both very much for the answers! \m/
Topic archived. No new replies allowed.