random number in [0, 99]

Q

quickcur

Hi, I am using the int version of rand() with MS Visual Studio. I would
like to generate random number in the range of [0, 99]. Right now I am
using

rand() * 100 / (RAN_MAX + 1)

I found that I got too much 0. 0 appears more than any other numbers.
How can I fix it?

Thanks,

qq
 
K

Keith Thompson

Hi, I am using the int version of rand() with MS Visual Studio. I would
like to generate random number in the range of [0, 99]. Right now I am
using

rand() * 100 / (RAN_MAX + 1)

I found that I got too much 0. 0 appears more than any other numbers.
How can I fix it?

See question 13.16 in the C FAQ, <http://www.c-faq.com/>.
 
C

Christian Bau

Hi, I am using the int version of rand() with MS Visual Studio. I would
like to generate random number in the range of [0, 99]. Right now I am
using

rand() * 100 / (RAN_MAX + 1)

I found that I got too much 0. 0 appears more than any other numbers.
How can I fix it?

If RAND_MAX > INT_MAX / 100, that would have to be expected and would be
entirely your fault. What would your code do if RAND_MAX == INT_MAX? You
might try

(int) (rand () * (100.0 / (RAND_MAX + 1.0)))

instead.
 
M

Martin Ambuhl

Hi, I am using the int version of rand() with MS Visual Studio. I would
like to generate random number in the range of [0, 99]. Right now I am
using

rand() * 100 / (RAN_MAX + 1)
^^ missing decimal point
1 is an integer,
RAN_MAX + 1 is an integer (but
may overflow)

rand() * 100 / (RAN_MAX + 1.0)
1.0 is floating point,
RAN_MAX + 1.0 is floating point
 
J

Joe Wright

Hi, I am using the int version of rand() with MS Visual Studio. I would
like to generate random number in the range of [0, 99]. Right now I am
using

rand() * 100 / (RAN_MAX + 1)

I found that I got too much 0. 0 appears more than any other numbers.
How can I fix it?

Thanks,

qq
The C-FAQ suggests something like..

rand() / (RAND_MAX / len + 1)

...where len in your case would be 100.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,175
Messages
2,570,942
Members
47,489
Latest member
BrigidaD91

Latest Threads

Top