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

前端 未结 3 1571
星月不相逢
星月不相逢 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:41

    An old post, but here it goes. Kindly accept & rate it if you like.

    int div_to_zero(int n, int d) { return n / d; }
    //as per C++11 standard note 80
    
    int div_up(int n, int d) {
        return n / d + (((n < 0) ^ (d > 0)) && (n % d));
    } //i.e. +1 iff (not exact int && positive result)
    
    int div_down(int n, int d) {
        return n / d - (((n > 0) ^ (d > 0)) && (n % d));
    } //i.e. +1 iff (not exact int && negative result)
    
    int div_to_nearest(int n, int d) {
        return (2*n - d + 2*(true&&(n<0^d>0))*d) / (2*d); 
    } //i.e. +-0.5 as per pre-rounding result sign, then div_to-zero 
    //it however rounds numbers like +/- 3.5 towards 0 and not even.
    

    Note: most modern compilers will use a single division operation for n/d and n%d used in conjunction. So performance wise these are best reducing memory moves.

提交回复
热议问题