Modulo %100

Hello,

Pleased to have found this forum, hope to learn a lot and help wherever I can in the distant future.

I have a question concerning a randomly generated number from 0 to 99

Here's what I found by searching the forums before posting:
`v1 = rand() % 100; // v1 in the range 0 to 99 `

Here's the code I'm using:
 ``12`` ``````int height = 5; height += rand() % 100;``````

I understand what it does but I'm not too sure why I need % 100 in there for it to be a number from 0 to 99.

How does one speak this snippet in pseudo code?

Like: Height is equal to height plus a number generated by the rand() function, we divide that number by 100 and the remainder is..? I'm understanding the process wrong but I can't figure out how it should sound
 I understand what it does but I'm not too sure why I need % 100 in there for it to be a number from 0 to 99.

When you divide a number x by number y, you will end up with a whole number plus some remainder which is always less than y. That is why, by calculating the modulus of 100, you will always get some number from 0 to 99. If you don't include a modulus operator and a maximum number, your random number can become really large.

 Like: Height is equal to height plus a number generated by the rand() function, we divide that number by 100 and the remainder is..? I'm understanding the process wrong but I can't figure out how it should sound

If height is height, rand() is r, and the denominator(what the number is being divided by) is d, then your instruction can be read as:
height is equal to height plus the remainder of r divided by d.

~Daleth~
Last edited on
 Like: Height is equal to height plus a number generated by the rand() function, we divide that number by 100 and the remainder is..? I'm understanding the process wrong but I can't figure out how it should sound

I think there's a misunderstanding here.
The symbol `%` designates the modulo operator, not the division operator.
See https://en.wikipedia.org/wiki/Operators_in_C_and_C%2B%2B#Arithmetic_operators
Your first explanation did it for me, the remainder will always be 0 to 99 or 0.00 to 0.99 otherwise it would have reached a new range, like 1.01 or 1.99 ticking over to 2.

Thanks!
 I'm not too sure why I need % 100 in there for it to be a number from 0 to 99

rand() returns a number between 0 and RAND_MAX. RAND_MAX is implementation defined, but guaranteed to be at least 32767 on any standard library implementation.
http://www.cplusplus.com/reference/cstdlib/RAND_MAX/?kw=RAND_MAX

So if you want a random number constrained to a particular range (0-99), you use the modulo operator to do that.
Topic archived. No new replies allowed.