我特别考虑的是如何在使用c#或Java等语言时显示分页控件。
如果我有x个项目,我想在每页y块中显示,需要多少页?
我特别考虑的是如何在使用c#或Java等语言时显示分页控件。
如果我有x个项目,我想在每页y块中显示,需要多少页?
当前回答
在测试中删除零分支的替代方法:
int pageCount = (records + recordsPerPage - 1) / recordsPerPage * (records != 0);
不确定这是否将工作在c#,应该在C/ c++。
其他回答
我为自己做了这个,感谢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来说太过了。 然而,我认为它是可读的,也适用于负数。
Ian提供的整数数学解决方案很好,但存在整数溢出错误。假设变量都是int,解决方案可以重写为使用长数学和避免错误:
int pageCount = (-1L + records + recordsPerPage) / recordsPerPage;
如果记录很长,则错误仍然存在。模解没有这个bug。
您需要执行浮点除法,然后使用ceiling函数将值四舍五入到下一个整数。
我有一个类似的需求,我需要将分钟转换为小时和分钟。我用的是:
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);
尼克·贝拉尔迪(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。