Python-style integer division & modulus in C

后端 未结 6 1392
轻奢々
轻奢々 2020-12-05 17:55

In Python and Ruby, signed integer division truncates towards negative infinity, and signed integer modulus has the same sign the second operand:

>>>         


        
6条回答
  •  渐次进展
    2020-12-05 18:30

    It delves into the ugly world of floats, but these give correct answers in Java:

    public static int pythonDiv(int a, int b) {
        if (!((a < 0) ^ (b < 0))) {
            return a / b;
        }
        return (int)(Math.floor((double)a/(double)b));
    }
    
    public static int pythonMod(int a, int b) {
        return a - b * pythonDiv(a,b);
    }
    

    I make no assertions about their efficiency.

提交回复
热议问题