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

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


当前回答

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

其他回答

对于records == 0, rjmunro解为1。正确的解是0。也就是说,如果您知道记录> 0(我确信我们都假设recordsPerPage > 0),那么rjmunro解决方案将给出正确的结果,并且没有任何溢出问题。

int pageCount = 0;
if (records > 0)
{
    pageCount = (((records - 1) / recordsPerPage) + 1);
}
// no else required

所有整数解都比浮点解更有效。

我做以下,处理任何溢出:

var totalPages = totalResults.IsDivisble(recordsperpage) ? totalResults/(recordsperpage) : totalResults/(recordsperpage) + 1;

并使用这个扩展,如果有0结果:

public static bool IsDivisble(this int x, int n)
{
           return (x%n) == 0;
}

此外,对于当前的页码(没有被问到,但可能有用):

var currentPage = (int) Math.Ceiling(recordsperpage/(double) recordsperpage) + 1;

下面的方法应该比上面的解决方案做得更好,但以性能为代价(由于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;
}

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

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);

你可以使用

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