我特别考虑的是如何在使用c#或Java等语言时显示分页控件。
如果我有x个项目,我想在每页y块中显示,需要多少页?
我特别考虑的是如何在使用c#或Java等语言时显示分页控件。
如果我有x个项目,我想在每页y块中显示,需要多少页?
当前回答
在测试中删除零分支的替代方法:
int pageCount = (records + recordsPerPage - 1) / recordsPerPage * (records != 0);
不确定这是否将工作在c#,应该在C/ c++。
其他回答
Ian提供的整数数学解决方案很好,但存在整数溢出错误。假设变量都是int,解决方案可以重写为使用长数学和避免错误:
int pageCount = (-1L + records + recordsPerPage) / recordsPerPage;
如果记录很长,则错误仍然存在。模解没有这个bug。
对于records == 0, rjmunro解为1。正确的解是0。也就是说,如果您知道记录> 0(我确信我们都假设recordsPerPage > 0),那么rjmunro解决方案将给出正确的结果,并且没有任何溢出问题。
int pageCount = 0;
if (records > 0)
{
pageCount = (((records - 1) / recordsPerPage) + 1);
}
// no else required
所有整数解都比浮点解更有效。
另一种替代方法是使用mod()函数(或'%')。如果有非零余数,则对除法的整数结果加1。
一个泛型方法,你可以迭代它的结果:
public static Object[][] chunk(Object[] src, int chunkSize) {
int overflow = src.length%chunkSize;
int numChunks = (src.length/chunkSize) + (overflow>0?1:0);
Object[][] dest = new Object[numChunks][];
for (int i=0; i<numChunks; i++) {
dest[i] = new Object[ (i<numChunks-1 || overflow==0) ? chunkSize : overflow ];
System.arraycopy(src, i*chunkSize, dest[i], 0, dest[i].length);
}
return dest;
}
你可以使用
(int)Math.Ceiling(((decimal)model.RecordCount )/ ((decimal)4));