Python-style integer division & modulus in C

后端 未结 6 1371
轻奢々
轻奢々 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条回答
  •  Happy的楠姐
    2020-12-05 18:37

    Here is a simple implementation of floored division and modulus in C89:

    #include 
    
    div_t div_floor(int x, int y)
    {
        div_t r = div(x, y);
        if (r.rem && (x < 0) != (y < 0)) {
            r.quot -= 1;
            r.rem  += y;
        }
        return r;
    }
    

    Here, div is used because it has well-defined behavior.

    If you're using C++11, here is a templated implementation of floored division and modulus:

    #include 
    
    template
    std::tuple div_floor(Integral x, Integral y)
    {
        typedef std::tuple result_type;
        const Integral quot = x / y;
        const Integral rem  = x % y;
        if (rem && (x < 0) != (y < 0))
            return result_type(quot - 1, rem + y);
        return result_type(quot, rem);
    }
    

    In C99 and C++11, you can avoid using div since the behavior of division and modulus in C are no longer depend on the implementation.

提交回复
热议问题