[Date Prev][Date Next] [Thread Prev][Thread Next] [Date Index] [Thread Index]

Re: random()



Shao Zhang wrote:

> Reply-To:
> Hi,
>         I have some trouble to generate a random number. Please help.
>         I use the current time for the seed:
>
>         unsigned int gen_magic()
>         {
>                 time_t  cur;
>                 char    *cur_time;
>
>                 time(&cur);
>                 cur_time = ctime(&cur);
>
>                 srandom((unsigned int) (atol(cur_time)));
>
>                 return random();
>         }
>
>         But everytime this function gets called, it is always return the same number:
>
>         +------------+
>         | number     |
>         +------------+
>         | 1362961854 |
>         | 1362961854 |
>         | 1362961854 |
>         | 1362961854 |
>         | 1362961854 |
>         | 1362961854 |
>         | 1362961854 |
>         +------------+
>
>         There must be a better way to do this. Please tell me...
>
>         Thanks.

What's wrong with:

         srandom((unsigned int) (atol(cur_time)));

? Well, notice above that cur_time is a char *. This pointer should have the same value
each time the program is run which is why you're getting the same answer. Try instead:

         srandom((unsigned int) (atol(cur)));

Which is what you really meant.

--
Jens B. Jorgensen
jjorgens@bdsinc.com



Reply to: