vdublevsky vdublevsky - 3 months ago 25
C++ Question

Modulus formula

I'm reading a C++ Primer 5th ed and i don't understand why is this true :


The modulus operator is defined so that if m and n are integers and n is nonzero,
then (m/n)*n + m%n is equal to m.


I decided to check this and the result was indeed true:

int m = 9;
int n = 2;
if ((m / n)*n + m%n == m)
std::cout << "true" << std::endl;


1) (m/n)*n == m (9)

2) m%n == 1

3) (m/n)*n + m%n == 10 NOT 9

Can somebody explain what is going on here?

Answer
(m/n)*n == m (9)

You did that calculation wrong. This are integers

9/2 == 4