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)
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
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
> 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.
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.
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.
probably know.
You might see if gettimeofday on your system can give you sub-second times,
but something like
srand((unsigned)time(0)*99 7+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
but something like
srand((unsigned)time(0)*99
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
ASKER
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)