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 <stdio.h>

#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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值