0

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??

2
  • Why would you expect 4 as a result? Commented Aug 30, 2013 at 11:47
  • This is supposed to implement periodic boundary condition, so resulting in 4 there would be handy. Commented Aug 30, 2013 at 11:51

1 Answer 1

3

It's because you're using an unsigned int, the signed int (-1) gets promoted to -1 % UINT_MAX so your operation becomes (-1 % UINT_MAX) % 5 = 0 (thanks to jrok for this more detailed reason)

try

cout << "\ta%b\t=\t" << a%(int)b << endl; result = a%(int)b; 

with function signature of: int my_mod(int a, unsigned int b)

Or just use a function signature of: int my_mod(int a, int b)

Sign up to request clarification or add additional context in comments.

2 Comments

It's actualy because of integer promotion, to be pedantic. -1 promoted to unsigned int yields UINT_MAX which is evenly divisible by 5.
OK, now that was just as fast as it was embarrassing for me. Sorry, I don't know how I could fail to see this. I haven't slept much since this error screw things over, granted. But this is bad. Thank you very, very much!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.