将两个整数相除并四舍五入结果,而无需使用浮点数 [英] Dividing two integers and rounding up the result, without using floating point

查看:51
本文介绍了将两个整数相除并四舍五入结果,而无需使用浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将两个数字相除并将其四舍五入.有更好的方法吗?

I need to divide two numbers and round it up. Are there any better way to do this?

int myValue = (int) ceil( (float)myIntNumber / myOtherInt );

我发现必须投入两个不同的时间来解决问题.(extern int强制转换只是为了关闭警告)

I find an overkill to have to cast two different time. (the extern int cast is just to shut down the warning)

请注意,我必须在内部进行强制转换才能以其他方式浮动

Note I have to cast internally to float otherwise

int a = ceil(256/11); //> Should be 24, but it is 23
              ^example

推荐答案

在DyP的帮助下,提出了以下无分支公式:

With help from DyP, came up with the following branchless formula:

int idiv_ceil ( int numerator, int denominator )
{
    return numerator / denominator
             + (((numerator < 0) ^ (denominator > 0)) && (numerator%denominator));
}

它避免了浮点转换,并通过了基本的单元测试套件,如下所示:

It avoids floating-point conversions and passes a basic suite of unit tests, as shown here:

这是避免模运算符的另一个版本.

Here's another version that avoids the modulo operator.

int idiv_ceil ( int numerator, int denominator )
{
    int truncated = numerator / denominator;
    return truncated + (((numerator < 0) ^ (denominator > 0)) &&
                                             (numerator - truncated*denominator));
}

  • http://ideone.com/Z41G5q
  • 在IDIV返回商和余数(并且编译器足够聪明地使用它)的处理器上,第一个会更快.

    The first one will be faster on processors where IDIV returns both quotient and remainder (and the compiler is smart enough to use that).

    这篇关于将两个整数相除并四舍五入结果,而无需使用浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆