Python-style integer division & modulus in C

后端 未结 6 1355
轻奢々
轻奢々 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

    The direction for rounding with signed integer division is not specified in older C standards. However, in C99 it is specified to round towards zero.

    Here's portable code which works with all versions of the C standards and CPU architectures:

    int py_div(int a, int b)
    {
      if (a < 0)
        if (b < 0)
          return -a / -b;
        else
          return -(-a / b) - (-a % b != 0 ? 1 : 0);
      else if (b < 0)
          return -(a / -b) - (a % -b != 0 ? 1 : 0);
        else
          return a / b;
    }
    
    int py_mod(int a, int b)
    {
      if (a < 0)
        if (b < 0)
          return -(-a % -b);
        else
          return -a % b - (-a % -b != 0 ? 1 : 0);
      else if (b < 0)
          return -(a % -b) + (-a % -b != 0 ? 1 : 0);
        else
          return a % b;
    }
    

    I did some superficial tests and it appears to give the same results as Python. This code may not be maximally efficient, but a good C compiler can probably optimize it adequately, especially if you put the code in a header as static functions.

    You may also want to take a look at this closely related question: Integer division rounding with negatives in C++.

提交回复
热议问题