Two things:
First, you are never assigning r
any value. You need to change 4.0*rand()/RAND_MAX+1;
to r = 4.0*rand()/RAND_MAX+1;
Second, the compiler will likely complain about that since you're degrading from double to int. You should change 4.0
to 4
.
The final code should look roughly like r = 4*rand()/RAND_MAX+1;
. Then, the range will be {1, 2, 3, 4, 5} (note: depends on whether rand
can return RAND_MAX
or only less than RAND_MAX
. If only less, then exclude 5.) If you wanted {0, 1, 2, 3} you needed to enclose RAND_MAX+1
in parentheses.
Note: as pointed out in the comments, there may be some concerns with the above. You can use something like this to get exactly the same distribution:
r = rand()
if (r == RAND_MAX) return 5;
else return r % 4 + 1;
If you don't ever want to return 5, you can use rejection sampling:
r = RAND_MAX;
while (r == RAND_MAX) r = rand();
return r % 4 + 1;