Random Numbers

i am trying to generate a random number between 0 and 1. i thought the code would look like:

 
rand() % 0 + 1;


i keep getting a warning "potential mod by 0"

another method i thought of was:

 
(double)rand() / (double)RAND_MAX;


but that doesn't seem to work either...

does anybody have any ideas? thanks.
rand() % 0 returns the reminder of the division rand() / 0 which isn't possible

(double)rand() / (double)RAND_MAX; should work, why do you say that it doesn't work?
 
(double)rand() / (double)RAND_MAX


seems to be giving me the same number everytime..am i using it wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
double getrand () 
{
   double probability, r; 
   cout << "How likely is the virus to spread to a neighbor (0 = never, 1 = certain)? "; 
   cin >> probability;

   while (probability > 1 || probability < 0) 
{
   cout << "please enter a number between 0 and 1 "; 
   cin >> probability;
}

srand (probability);
r = (double)rand () / (double) RAND_MAX; 
return r;

}
You should call srand only once on your program
Last edited on
srand seeds the RNG. In order to get random numbers, you need to provide a seed that is, itself, somewhat random. Typically this is done by using the current time:

 
srand( time(0) );


Since srand() takes a unsigned integer as its seed, and not a double, your 'probability' is being truncated to either 0 or 1 (usually 0). So your above srand is not very effective.

+ what Bazzy said. Only call srand once. Like when your program first starts up.
ok, so srand() should be in main, not in my function. thank you.

what about the seed? if the user is entering a probability, should that probability be the seed?

srand(probability)?
sorry..didn't see your post disch..thanks
rand() % x is calling for random integers within a range of x from 0 up. rand()%3 gives you

random numbers from 0-2. rand()%2 should give you 0s and 1s. rand() % 1 will give you

just 0s. so rand() % 0 is basically asking for nothing. personally i like that notation better

than(double)rand () / (double) RAND_MAX


side note (rand()%2)+1 is essentially a) getting random number 0 or 1 then b) adding

one to that number. in your rand()%0 +1 you

were using the +1 to add one to a nonexistant number. for 0s and 1s just use rand()%2


so you can stick with (double)rand () / (double) RAND_MAX or use rand%2 doesnt really

just good to understand how they both work
Topic archived. No new replies allowed.