By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
 429,101 Members | 1,340 Online + Ask a Question
Need help? Post your question and get tips & solutions from a community of 429,101 IT Pros & Developers. It's quick & easy.

# How to generate a random number

 100+ P: 151 Hi, i am generating random number 10000 times but i want outof 3400000 times, there should be 10000 times it should be zero. How can i implement this? int i = 0; while(i<3400000) { int r_number= rand() % 10000; if(r_number == 0) { // do something } i++; } i need r_number should be zero 10000 times. I have tried but nothing seem to be working. Thanks in advance. Nov 18 '10 #1
Share this Question
2 Replies

 100+ P: 1,059 it means Random are not returning number which is divisible by 10000. What is the range of random? what is your expecting range? I cant recall that either... Nov 18 '10 #2

 Expert Mod 5K+ P: 8,916 No you are generating a random number 340000 times. Look at your odds, you generate a random number X in the range 0 <= X < 10000. So the change it is 0 is 1/10000. If you are generating 340000 that means you can expect around 340000 * 1/10000 or 340000 / 10000 or 340 to be 0. This is born out if you add just a little output to your program like this Expand|Select|Wrap|Line Numbers #include "stdlib.h" #include "stdio.h" #include "time.h"   int main() {     int i = 0;     int zero = 0;       srand(time(NULL));       while(i<3400000)     {         int r_number= rand() % 10000;         if(r_number == 0)         {         // do something             printf("0 at %d\n", i);             zero++;         }           i++;     }       printf("Total 0: %d\n", zero);       return 0; }   If you want 10,000 0 then you need to either alter the the number of iterations of the while loop or you need to alter the probability of getting a zero by altering the range of the random numbers you are generating or you need to alter both such that * = 10000 Nov 18 '10 #3

### Post your reply

Sign in to post your reply or Sign up for a free account. 