Link to home
Start Free TrialLog in
Avatar of idek1
idek1

asked on

Random Numbers

I am trying to write a program which will print out a different random number each time it is executed.

Here is what I have so far:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void main()
{
unsigned int number;
time_t t;

      srand((unsigned)time(&t));
      number = rand() % 100;
      printf("%d", number);
}

Unfortunately this question has the effect of only changing the random number once every second, and so if this program is run five times within one second the same number is generated.
If somebody could suggest a way of writing this program so that a different number is generated EVERY time it is run.
(intended platform is Unix)
ASKER CERTIFIED SOLUTION
Avatar of yonat
yonat

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of idek1
idek1

ASKER

The ideas of using process ID etc. are quite good, however, having only recently been enlightened to Unix, I am not confident  that I know the right functions to use to get this information.
How would I, for example, obtain the current process number, and would this number change if the program was run 5 times in a row in a very short time? ( < 1 sec)


>  the right functions to use to get this information

I am not a Uniz wiz myself, so I can't help you there - sorry.

> would [the process ID] change if the program was run 5 times in
> a row in a very short time

Not necessarily. This is why you need to use a combination of
pseudo-random entities: The ticks since startup *would* change in
this case.
Avatar of idek1

ASKER

Anybody else know how to get the ticks since startup in Unix?
:)

You could try asking this in the Unix Programming area. They'll
probably know.
Avatar of ozo
You might see if gettimeofday on your system can give you sub-second times,
but something like
  srand((unsigned)time(0)*997+getpid()*991);
is probaly good enough. I doubt you can wrap the pid in under a second,
and even if you did, the rand() % 100 is probably the weak link anyway.
I'd change to random and srandom before trying to improve the seed furthur