i want to use rand function for finding random number with 4 digits how can i do that
im only knowing how to find the maximum number which is x=rand()%10000 but how can i tell it for finding minimum number 1000
i want to use rand function for finding random number with 4 digits how can i do that
im only knowing how to find the maximum number which is x=rand()%10000 but how can i tell it for finding minimum number 1000
Code:#include <time.h> #include <stdio.h> int main (void) { int x; int y; srand(Time(0)); // seed the random number generator. for( y = 0; y < 100; y++) { x = (rand() % 9000) + 1000; // get random number in range 1000 - 9999 printf("%d\t", x); } return 0; }
is any other combination for this? x = (rand() % 9000) + 1000;
or is the only way i can do it
There are plenty of ways to do it. One could even say that there are an infinite number of ways to do it.
Here's it done using the rejection method, which is not biased compared to the above:As you can see it takes much more code so you may be perfectly happy with the first method.Code:int x; do { x = rand(); } while (x >= (RAND_MAX / 9000) * 9000); x = x % 9000 + 1000;
My homepage
Advice: Take only as directed - If symptoms persist, please see your debugger
Linus Torvalds: "But it clearly is the only right way. The fact that everybody else does it some other way only means that they are wrong"
Originally Posted by The Jargon File