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

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


当前回答

在测试中删除零分支的替代方法:

int pageCount = (records + recordsPerPage - 1) / recordsPerPage * (records != 0);

不确定这是否将工作在c#,应该在C/ c++。

其他回答

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

如何在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毫秒,相当长的时间。

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

这应该能给你想要的。你肯定想要每页x个项目除以y个项目,问题是当出现不平衡的数字时,所以如果有一个部分页面,我们也想增加一页。

int x = number_of_items;
int y = items_per_page;

// with out library
int pages = x/y + (x % y > 0 ? 1 : 0)

// with library
int pages = (int)Math.Ceiling((double)x / (double)y);

下面的方法应该比上面的解决方案做得更好,但以性能为代价(由于0.5* rct分母的浮点计算):

uint64_t integerDivide( const uint64_t& rctNumerator, const uint64_t& rctDenominator )
{
  // Ensure .5 upwards is rounded up (otherwise integer division just truncates - ie gives no remainder)
  return (rctDenominator == 0) ? 0 : (rctNumerator + (int)(0.5*rctDenominator)) / rctDenominator;
}