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

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


当前回答

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

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

其他回答

找到了一个优雅的解决方案:

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

资料来源:《数字转换》,罗兰·巴恪思,2001年

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

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

如何在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来说太过了。 然而,我认为它是可读的,也适用于负数。

在测试中删除零分支的替代方法:

int pageCount = (records + recordsPerPage - 1) / recordsPerPage * (records != 0);

不确定这是否将工作在c#,应该在C/ c++。