My program returns the same value every time I run it:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int randomNum = rand() % 100;
printf("random number: %d", randomNum);
}
Why is this and how can I fix it?
My program returns the same value every time I run it:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int randomNum = rand() % 100;
printf("random number: %d", randomNum);
}
Why is this and how can I fix it?
That's because rand
is a pseudo-random number generator, which means it returns the same sequence for any given input (the input is by default 1).
You can seed the random number generator with the time to get a different value each time you run your program:
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
struct timespec ts;
timespec_get(&ts, TIME_UTC);
srand(ts.tv_sec ^ ts.tv_nsec);
int random_num = rand() % 100;
printf("random number: %d", random_num);
}
If you have POSIX you can also add a + getpid()
to srand
's argument and #include <stdlib.h>
.