我特别考虑的是如何在使用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;
}

其他回答

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

我有一个类似的需求,我需要将分钟转换为小时和分钟。我用的是:

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

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

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

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

这应该能给你想要的。你肯定想要每页x个项目除以y个项目,问题是当出现不平衡的数字时,所以如果有一个部分页面,我们也想增加一页。

int x = number_of_items;
int y = items_per_page;

// with out library
int pages = x/y + (x % y > 0 ? 1 : 0)

// with library
int pages = (int)Math.Ceiling((double)x / (double)y);

另一种替代方法是使用mod()函数(或'%')。如果有非零余数,则对除法的整数结果加1。