Random numbers

I am wrote a fuction to randomly generate stats for a computer opponent. My problem is that srand(time(0)) does not generate new numbers fast enough. I need 5-8 random numbers, 1 for each stat.

Here is a small piece of the for loop I am using to generate a value for each stat.
1
2
3
4
5
6
7
8
9
10
        for (c=1; c<5;c++)            // for each stat 
        {
            srand(time(0));
            randomNumber = rand();   // random number
            m = ((randomNumber %10)+3); 

            if (c==1) 
            {
                cstr = (m*lvl);      // opponent's stat
            }


What do you suggest I do?
Last edited on
What do you mean with fast enough???
Exactly what I said, srand(time(0)) generates a different number every second, I think. This funtion calls srand for each of the 5 stats I am using in my game. C++ is able to run thru the code almost instantly.

My book only offers srand(time(0)) for generating new numbers. Is there something else I can use, or a different way of writing the code so that each instance of the loop generates a new number?
Only use srand(time(0)) once. That seeds the rand() function which will give you a random number each time.


[code=cpp] srand(time(0));
for (c=1; c<5;c++) // for each stat
{
m = (rand() % 10) + 3; // random number

if (c==1)
{
cstr = (m*lvl); // opponent's stat
}[/code]

Last edited on
=[ that didnt work either Cheesy. All 5 stats still have the same value.

--edit--

Looks like I got it. Thank you for your help locorecto and CheesyBeefy

1
2
3
4
5
        for (c=1; c<5;c++)
        {
            srand(time(0)*m);
            randomNumber = rand();
            m = ((randomNumber %10)+3); 
Last edited on
hi ,
I'm a french beginner on C++.
i try to generate hasard with a programm to choose randown number.I have already write this code:


#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
long n = 0;
srand(time(NULL));
n = rand();
do
{
printf("%ld",n);
} while (getchar()!='Q');

return 0;
}




What does i do if i want choose a randown number n betwween 0 and 54.
I dont want use loops or if fonctions.
ty for your help.
I think you should use "rand() % 54 + 1", in the place of the rand().
ty for you help HeatMan
gd566 that won't work.

You need to call srand() exactly ONCE in your program. Subsequent to that, calls to rand() will -- must -- return unique numbers until the RNGs cycle expires (2^32).

Topic archived. No new replies allowed.