我想确保整数的除法在必要时总是四舍五入。还有比这更好的办法吗?有很多演员都在选角。: -)

(int)Math.Ceiling((double)myInt1 / myInt2)

当前回答

使用扩展方法的绝佳机会:

public static class Int32Methods
{
    public static int DivideByAndRoundUp(this int number, int divideBy)
    {                        
        return (int)Math.Ceiling((float)number / (float)divideBy);
    }
}

这使得你的代码超级可读:

int result = myInt.DivideByAndRoundUp(4);

其他回答

对于有符号整数或无符号整数。

Q = x / y + !(((x < 0) != (y < 0)) || !(x % y));

有符号的股利和无符号的因子。

Q = x / y + !((x < 0) || !(x % y));

对于无符号股利和有符号因子。

Q = x / y + !((y < 0) || !(x % y));

对于无符号整数。

Q = x / y + !!(x % y);

零除数失败(与本机操作一样)。

不能溢出。

优雅而正确。

理解这种行为的关键是认识到截断、下限和上限划分的区别。c# / c++是被截断的。当商为负(即运算符符号不同)时,截断是一个上限(更少的负)。否则截断是一个底(不太正)。

因此,如果有余数,如果结果为正,则加1。模也是一样的,只是加了除数。地板是一样的,但是在相反的条件下减去。

使用扩展方法的绝佳机会:

public static class Int32Methods
{
    public static int DivideByAndRoundUp(this int number, int divideBy)
    {                        
        return (int)Math.Ceiling((float)number / (float)divideBy);
    }
}

这使得你的代码超级可读:

int result = myInt.DivideByAndRoundUp(4);

到目前为止,这里所有的答案似乎都过于复杂。

在c#和Java中,对于正的被除数和除数,你只需要做:

( dividend + divisor - 1 ) / divisor 

资料来源:《数字转换》,罗兰·巴恪思,2001年

上面的一些答案使用浮动,这是低效的,真的没有必要。对于无符号整数,这是int1/int2的有效答案:

(int1 == 0) ? 0 : (int1 - 1) / int2 + 1;

对于有符号int型,这是不正确的

您可以编写一个helper。

static int DivideRoundUp(int p1, int p2) {
  return (int)Math.Ceiling((double)p1 / p2);
}