For example the code below
int a = -7777;
int b = 10;
cout<< a % b<<endl;
cout<<(a+b)%b<<endl;
cout<< -7777%10 <<endl;
The results are:
-7
-7
-7
but if I changed the type of b to unsigned int, it has different values;
int a = -7777;
unsigned int b = 10;
cout<< a % b<<endl;
cout<<(a+b)%b<<endl;
cout<< -7777%10 <<endl;
The resutls are
9
9
-7
Could any body advise how it is working here? How do the differences come?
Btw: I am using C++ in Xcode latest version.
b
to-7777 = 10 * a + b
wherea
is any integer and0 <= b < 10
). Although of course-7
is closest because it is equivalent to3
modulo 10. – Presber(0 <= r < |b|)
would have been the superior choice; mathematically, it exhibits a regularity the other conventions don't, and leaves no ambiguity. That doesn't make the other answers 'incorrect' (mod 10) in this case - they're just different conventions. – Impure