一、由于两数相除,默认是向下取整,要想向下取整数,就得用下面的宏。
#define DIV_ROUND_UP(n,d) (((n) + (d) - 1) / (d))
二、由于两数相除,四舍五入方法.
2.1 内核标准的宏
#define DIV_ROUND_CLOSEST(x, divisor)( \
{ \
typeof(x) __x = x; \
typeof(divisor) __d = divisor; \
(((typeof(x))-1) > 0 || \
((typeof(divisor))-1) > 0 || (__x) > 0) ? \
(((__x) + ((__d) / 2)) / (__d)) : \
(((__x) - ((__d) / 2)) / (__d)); \
} \
)
2.2 如果确认都在整数的话直接用,这样比较好能理解
#define DIV_ROUND_CLOSEST(n, d) (2 * n + d ) / (2 * d)
三、测试C语言代码
#include
#define DIV_ROUND_UP(n,d) (((n) + (d) - 1) / (d))
#define DIV_ROUND_CLOSEST(x, divisor)( \
{ \
typeof(x) __x = x; \
typeof(divisor) __d = divisor; \
(((typeof(x))-1) > 0 || \
((typeof(divisor))-1) > 0 || (__x) > 0) ? \
(((__x) + ((__d) / 2)) / (__d)) : \
(((__x) - ((__d) / 2)) / (__d)); \
} \
)
//#define DIV_ROUND_CLOSEST(n, d) (2 * n + d ) / (2 * d)
int main () {
int a = 2;
int b = 3;
int c = 2 / 3;
printf("c=:%d\n",c);
printf("DIV_ROUND_UP(2,3) = %d\n",DIV_ROUND_UP(1,3));
printf("DIV_ROUND_UP(1,3) = %d\n",DIV_ROUND_UP(2,3));
printf("DIV_ROUND_CLOSEST(1,3) = %d\n",DIV_ROUND_CLOSEST(1,3));
printf("DIV_ROUND_CLOSEST(2,3) = %d\n",DIV_ROUND_CLOSEST(2,3));
printf("DIV_ROUND_CLOSEST(2,5) = %d\n",DIV_ROUND_CLOSEST(2,5));
printf("DIV_ROUND_CLOSEST(3,5) = %d\n",DIV_ROUND_CLOSEST(3,5));
printf("DIV_ROUND_CLOSEST(47,5) = %d\n",DIV_ROUND_CLOSEST(47,5));
printf("DIV_ROUND_CLOSEST(48,5) = %d\n",DIV_ROUND_CLOSEST(48,5));
return 0;
}
标准输出:
c=:0
DIV_ROUND_UP(2,3) = 1
DIV_ROUND_UP(1,3) = 1
DIV_ROUND_CLOSEST(1,3) = 0
DIV_ROUND_CLOSEST(2,3) = 1
DIV_ROUND_CLOSEST(2,5) = 0
DIV_ROUND_CLOSEST(3,5) = 1
DIV_ROUND_CLOSEST(47,5) = 9
DIV_ROUND_CLOSEST(48,5) = 10