I need help with this code I have written. The problem is that I want it to generate random numbers from 1000 to 9999. But if you run it, it returns numbers higher than 9999. I have read some forums about the correct way to use rand()
but am still stuck.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int w = 0;
int mi;
int i;
srand(time(0));
for(i=0;i<=20;i++)
{
mi= rand() % 9999+1000;
printf("%d\n",mi);
}
return 0;
}
If you want numbers from 1000 to 9999, that means you want values from a range of 9000 numbers. So that value needs to be your modulus, not 9999.
mi = rand() % 9000 + 1000;