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

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


当前回答

我为自己做了这个,感谢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来说太过了。 然而,我认为它是可读的,也适用于负数。

其他回答

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

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

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

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

尼克·贝拉尔迪(Nick Berardi)回答的一个变种,避开了一个分支:

int q = records / recordsPerPage, r = records % recordsPerPage;
int pageCount = q - (-r >> (Integer.SIZE - 1));

备注:(-r >>(整数。SIZE - 1))由r的符号位组成,重复32次(感谢>>操作符的符号扩展)。如果r为0或负,它的值为0,如果r为正,它的值为-1。如果记录% recordsPerPage > 0,那么从q中减去它的效果是加1。

Ian提供的整数数学解决方案很好,但存在整数溢出错误。假设变量都是int,解决方案可以重写为使用长数学和避免错误:

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

如果记录很长,则错误仍然存在。模解没有这个bug。

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

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;