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

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


当前回答

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

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;

其他回答

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

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

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

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

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

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

另一种替代方法是使用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);