我特别考虑的是如何在使用c#或Java等语言时显示分页控件。

如果我有x个项目,我想在每页y块中显示,需要多少页?


当前回答

你可以使用

(int)Math.Ceiling(((decimal)model.RecordCount )/ ((decimal)4));

其他回答

另一种替代方法是使用mod()函数(或'%')。如果有非零余数,则对除法的整数结果加1。

我有一个类似的需求,我需要将分钟转换为小时和分钟。我用的是:

int hrs = 0; int mins = 0;

float tm = totalmins;

if ( tm > 60 ) ( hrs = (int) (tm / 60);

mins = (int) (tm - (hrs * 60));

System.out.println("Total time in Hours & Minutes = " + hrs + ":" + mins);

您需要执行浮点除法,然后使用ceiling函数将值四舍五入到下一个整数。

我为自己做了这个,感谢Jarod Elliott和SendETHToThisAddress的回复。

public static int RoundedUpDivisionBy(this int @this, int divider)
{        
    var result = @this / divider;
    if (@this % divider is 0) return result;
    return result + Math.Sign(@this * divider);
}

然后我意识到,与上面的答案相比,它对CPU来说太过了。 然而,我认为它是可读的,也适用于负数。

如何在c#中四舍五入整数除法的结果

我有兴趣知道在c#中做这件事的最好方法是什么,因为我需要在循环中做这件事近10万次。其他人使用Math发布的解决方案在答案中排名靠前,但在测试中我发现它们很慢。Jarod Elliott提出了一个更好的策略来检查mod是否产生任何东西。

int result = (int1 / int2);
if (int1 % int2 != 0) { result++; }

我循环运行了100万次,花了8毫秒。下面是使用Math的代码:

int result = (int)Math.Ceiling((double)int1 / (double)int2);

在我的测试中运行了14毫秒,相当长的时间。