C++ functions for integer division with well defined rounding strategy

前端 未结 3 1579
星月不相逢
星月不相逢 2021-02-06 06:14

I want something in C++ that lets me do efficient integer division with specified rounding behavior, something like this:

div_down(-4,3)        ==> -2
div_up(         


        
3条回答
  •  猫巷女王i
    2021-02-06 06:36

    This is what I've got so far, with the precondition d > 0. They all seem to work, but can they be simplified?

    int div_down(int n, int d) {
      if (n < 0) {
        return -((d - n - 1) / d);
      } else {
        return n / d;
      }
    }
    
    int div_up(int n, int d) {
      if (n < 0) {
        return -(-n / d);
      } else {
        return (n + d - 1) / d;
      }
    }
    
    int div_to_zero(int n, int d) {
      return n / d;
    }
    
    int div_to_nearest(int n, int d) {
      if (n < 0) {
        return (n - d/2 + 1) / d;
      } else {
        return (n + d/2) / d;
      }
    }
    

提交回复
热议问题