2023-07-07 C语言两数相除向下取整DIV_ROUND_UP(n,d),两数相除四舍五入DIV_ROUND_CLOSEST

一、由于两数相除,默认是向下取整,要想向下取整数,就得用下面的宏。

#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

你可能感兴趣的:(c语言,算法,开发语言)