Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modulo with a negative integer in C++ [duplicate]

Tags:

c++

modulo

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.

like image 956
Basj Avatar asked Mar 15 '26 17:03

Basj


1 Answers

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; }
like image 136
2 revsBasj Avatar answered Mar 17 '26 11:03

2 revsBasj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!