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

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


当前回答

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

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

其他回答

这应该能给你想要的。你肯定想要每页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);

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

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;

在CPU级别上,转换为浮点数和返回浮点数似乎是一种巨大的时间浪费。

伊恩·尼尔森的解决方案:

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

可以简化为:

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

AFAICS,它没有Brandon DuRette指出的溢出错误,并且因为它只使用一次,所以您不需要存储recordsPerPage,特别是如果它来自一个从配置文件或其他东西获取值的昂贵函数。

例如,这可能是低效的,如果配置。Fetch_value使用了数据库查找之类的:

int pageCount = (records + config.fetch_value('records per page') - 1) / config.fetch_value('records per page');

这会创建一个你并不真正需要的变量,这可能有(轻微的)内存影响,并且输入太多:

int recordsPerPage = config.fetch_value('records per page')
int pageCount = (records + recordsPerPage - 1) / recordsPerPage;

这都是一行,只获取一次数据:

int pageCount = (records - 1) / config.fetch_value('records per page') + 1;

找到了一个优雅的解决方案:

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

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

对于c#,解决方案是将值强制转换为double类型(如Math。天花板是双人间):

int nPages = (int)Math.Ceiling((double)nItems / (double)nItemsPerPage);

在java中,您应该对Math.ceil()执行相同的操作。