Hello. I'm running a game online and designing a program to help me generate Enemy Stats. Basically, it's supposed to generate 25 numbers between 0 and 7(to represent 8 Attributes on a 25 Point Buy system) and count how many times each number shows up.
Here's what the code looks like:
Code:
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;
int Generate()
{
int r= rand();
int s= r%7;
cout<<r<<"\t"<<s<<endl;
return s;
}
int main()
{
int Stats[8];
for(int i=0; i<=8; i++)
{
Stats[i]=0;
}
for (int i=0; i<25; i++)
{
srand(time(NULL));
int x= Generate();
Stats[x]++;
}
for(int i=0; i<=8; i++)
{
cout<<"Stats["<<i<<"]= "<<Stats[i]<<endl;
}
}
This will give you 7 random numbers (between 0 and 6) and not 8 as you probably want,
Code:
int r= rand();
int s= r%7;
And this will loop 9 times giving indexes between 0 and 8 (of which the last will fall outside the 8 element array),
Code:
for(int i=0; i<=8; i++)
Then the problem with the random numbers. You call srand(parameter) to select a random sequence. Each parameter is associated with one random sequence. It's usually enought to do this only once in a program. So move
Code:
srand(time(NULL));
to the beginning of the program or at least outside the loop where it now resides.
In principle you could keep it where it sits now if you changed the call to srand(i). Then rand() would return a different random number in each iteration of the loop. But this would be the first random number of a different random sequence and that would be unfortunate for two reasons. First you have no guarantee that the random numbers so selected will be independent (and this means you unwittingly degrade the quality or the random generator). And second the numbers will be the same in each run of the program (which you obviously don't want since you seed from the system timer).
Still the question of why you always get the same random numbers hasn't been answered. It's because of the resolution of time(). It only ticks/changes once a millisecond or so. This means when it's called several times in quick succession it will return the same time. And this means srand() is seeded with the same parameter and rand() will always return the first random number of the same random sequence.
Last edited by nuzzle; September 29th, 2012 at 10:53 AM.
To cut a long story short for you, this part of Nuzzle's reple says it all about your program.
Still the question of why you always get the same random numbers hasn't been answered. It's because of the resolution of time(). It only ticks/changes once a millisecond or so. This means when it's called several times in quick succession it will return the same time. And this means srand() is seeded with the same parameter and rand() will always return the first random number of the same random sequence.
Also, if these replies have satisfied you, you should mark this thread as resolved.
Bookmarks