3

Why does -26 % 10 output -6 in C++ ?

How to get the standard modulo, that would output 4 ?


Note: this question is probably a duplicate of this one, or many others, but I haven't found one formulated in a short way, understandable in an eye blink. And as I personnaly like finding short questions / short answers (for simple issues), I thought it may interest other people. I'll delete this notice later.

Community
  • 1
  • 1
Basj
  • 41,386
  • 99
  • 383
  • 673

1 Answers1

15

One needs to do

(-26 % 10 + 10) % 10

to get 4.

For future reference :

int mod(int a, int b) { return (a % b + b) % b; }
Basj
  • 41,386
  • 99
  • 383
  • 673
  • 2
    Why not add the answer to the dupe target? And what is with the CW? If you did it to avoid the rep penalty from down votes then that right there proves this is not the correct way to handle this situation. – NathanOliver Jul 07 '16 at 17:00
  • @NathanOliver All these questions don't meet the "two lines max" question and "two lines max" answer criteria. Too much fuss fur a simple matter. Thus this (community wiki) question / answer. – Basj Jul 07 '16 at 17:01
  • @NathanOliver : your comment is wrong : `(-26 % 10 + 10) % 10` **is** `4`, see http://cpp.sh/44q4q – Basj Jul 07 '16 at 17:13
  • @LightnessRacesinOrbit FYI that was a response to a comment I deleted since it was wrong. I made a math mistake. – NathanOliver Jul 07 '16 at 17:17
  • @LightnessRacesinOrbit sorry, but for correctness, Nathan's comment stated `(-26 % 10 + 10) % 10 is 6` and suggested to use abs(...) which is wrong. – Basj Jul 07 '16 at 17:17
  • I still don't know how -26 % 10 should give the standard result of 4 though. – NathanOliver Jul 07 '16 at 17:17
  • 1
    @NathanOliver: Because that is proper modulo arithmetic. If you keep adding 10 starting from -26 until you get a positive number, you get 4. – Benjamin Lindley Jul 07 '16 at 17:20
  • @BenjaminLindley Thanks. I have only ever approached modulo math the C++ way. Didn't know it worked the other way. I see my MS calculator uses the C++ way but google uses the other way – NathanOliver Jul 07 '16 at 17:22