Conrad Albrecht Conrad Albrecht - 4 months ago 15
C# Question

How to integer-divide round negative numbers *down*?

Seems like whenever I divide a negative int by a positive int, I need it to round down (toward -inf), not toward 0. But both C# and C++ round toward 0.

So I guess I need a DivideDownward() method. I can write it in a few lines with a test for negative and so on, but my ideas seem klugey. So I'm wondering if I'm missing something and if you have an "elegant" way to round negative division downward.

Cam Cam
Answer

WARNING: this post produces incorrect results for input with a=-1. Please see other answers. -Cam


[c++]

This is probably what you meant by 'kludgey', but it's what I came up with ;)

int divideDown(int a, int b){
    int r=a/b;
    if (r<0 && r*b!=a)
        return r-1;
    return r;
}

In the if statement, I put r<0 - however I'm not sure if that's what you want. You may wish to change the if statement to

if (a<0 && b>0)

which would be consistent with your description "Seems like whenever I divide a negative int by a positive int ".

Comments