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

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


当前回答

你可以使用

(int)Math.Ceiling(((decimal)model.RecordCount )/ ((decimal)4));

其他回答

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

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

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

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

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

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

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

如何在c#中四舍五入整数除法的结果

我有兴趣知道在c#中做这件事的最好方法是什么,因为我需要在循环中做这件事近10万次。其他人使用Math发布的解决方案在答案中排名靠前,但在测试中我发现它们很慢。Jarod Elliott提出了一个更好的策略来检查mod是否产生任何东西。

int result = (int1 / int2);
if (int1 % int2 != 0) { result++; }

我循环运行了100万次,花了8毫秒。下面是使用Math的代码:

int result = (int)Math.Ceiling((double)int1 / (double)int2);

在我的测试中运行了14毫秒,相当长的时间。