my_mod.cpp:
#include <iostream> using namespace std; unsigned int my_mod(int a, unsigned int b) { int result; cout << "\ta\t=\t" << a << endl; cout << "\tb\t=\t" << b << endl; cout << "\ta%b\t=\t" << a%b << endl; result = a%b; if (result < 0) {result += b;} return result; } int main() { cout << "-1%5 = " << -1%5 << endl; cout << "my_mod(-1,5) = " << my_mod(-1,5) << endl; return 0; } compiled via: g++ ./my_mod.cpp
results in:
-1%5 = -1 a = -1 b = 5 a%b = 0 my_mod(-1,5) = 0 What the actual hell is happening here I just can't understand what possibly could go on?! This can't be due to the global scope, right?! I mean it is exactly the same %-expression ... how can they yield 0 and -1?! (Instead of the desired 4, by the way.)
Please, if anybody can, explain this to me ... it just took me days to narrow down an error in a wider context to this. Seriously, I'm about to cry.
How can I have my (global) own modulus returning 4 in the example above??