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

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


当前回答

一个泛型方法,你可以迭代它的结果:

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

您需要执行浮点除法,然后使用ceiling函数将值四舍五入到下一个整数。

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

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

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

如何在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毫秒,相当长的时间。

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