C# 如何舍入整数除法的结果?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17944/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to round up the result of integer division?
提问by Ian Nelson
I'm thinking in particular of how to display pagination controls, when using a language such as C# or Java.
我特别考虑在使用 C# 或 Java 等语言时如何显示分页控件。
If I have xitems which I want to display in chunks of yper page, how many pages will be needed?
如果我想在每页y块中显示x 个项目,需要多少页?
采纳答案by Ian Nelson
Found an elegant solution:
找到了一个优雅的解决方案:
int pageCount = (records + recordsPerPage - 1) / recordsPerPage;
回答by Kibbee
You'll want to do floating point division, and then use the ceiling function, to round up the value to the next integer.
您需要进行浮点除法,然后使用天花板函数将值向上舍入为下一个整数。
回答by Jarod Elliott
Another alternative is to use the mod() function (or '%'). If there is a non-zero remainder then increment the integer result of the division.
另一种选择是使用 mod() 函数(或“%”)。如果存在非零余数,则增加除法的整数结果。
回答by Nick Berardi
This should give you what you want. You will definitely want x items divided by y items per page, the problem is when uneven numbers come up, so if there is a partial page we also want to add one page.
这应该给你你想要的。您肯定希望每页将 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);
回答by Huppie
For C# the solution is to cast the values to a double (as Math.Ceiling takes a double):
对于 C#,解决方案是将值转换为双精度值(因为 Math.Ceiling 采用双精度值):
int nPages = (int)Math.Ceiling((double)nItems / (double)nItemsPerPage);
In java you should do the same with Math.ceil().
在 java 中,你应该对 Math.ceil() 做同样的事情。
回答by Brandon DuRette
The integer math solution that Ian provided is nice, but suffers from an integer overflow bug. Assuming the variables are all int
, the solution could be rewritten to use long
math and avoid the bug:
Ian 提供的整数数学解决方案很好,但存在整数溢出错误。假设变量都是int
,可以重写解决方案以使用long
数学并避免错误:
int pageCount = (-1L + records + recordsPerPage) / recordsPerPage;
int pageCount = (-1L + records + recordsPerPage) / recordsPerPage;
If records
is a long
, the bug remains. The modulus solution does not have the bug.
如果records
是long
,则错误仍然存在。模数解没有这个bug。
回答by rjmunro
Converting to floating point and back seems like a huge waste of time at the CPU level.
在 CPU 级别转换为浮点和返回似乎是一种巨大的时间浪费。
Ian Nelson's solution:
伊恩纳尔逊的解决方案:
int pageCount = (records + recordsPerPage - 1) / recordsPerPage;
Can be simplified to:
可以简化为:
int pageCount = (records - 1) / recordsPerPage + 1;
AFAICS, this doesn't have the overflow bug that Brandon DuRette pointed out, and because it only uses it once, you don't need to store the recordsPerPage specially if it comes from an expensive function to fetch the value from a config file or something.
AFAICS,这没有 Brandon DuRette 指出的溢出错误,并且因为它只使用一次,所以如果它来自一个昂贵的函数来从配置文件中获取值,则不需要专门存储记录 PerPage 或某物。
I.e. this might be inefficient, if config.fetch_value used a database lookup or something:
即这可能效率低下,如果 config.fetch_value 使用数据库查找或其他东西:
int pageCount = (records + config.fetch_value('records per page') - 1) / config.fetch_value('records per page');
This creates a variable you don't really need, which probably has (minor) memory implications and is just too much typing:
这会创建一个您并不真正需要的变量,它可能具有(轻微的)内存影响,并且键入太多:
int recordsPerPage = config.fetch_value('records per page')
int pageCount = (records + recordsPerPage - 1) / recordsPerPage;
This is all one line, and only fetches the data once:
这都是一行,并且只获取一次数据:
int pageCount = (records - 1) / config.fetch_value('records per page') + 1;
回答by Mike
For records == 0, rjmunro's solution gives 1. The correct solution is 0. That said, if you know that records > 0 (and I'm sure we've all assumed recordsPerPage > 0), then rjmunro solution gives correct results and does not have any of the overflow issues.
对于记录 == 0,rjmunro 的解决方案给出了 1。正确的解决方案是 0。也就是说,如果您知道记录 > 0(并且我确定我们都假设 recordPerPage > 0),那么 rjmunro 解决方案会给出正确的结果并且没有任何溢出问题。
int pageCount = 0;
if (records > 0)
{
pageCount = (((records - 1) / recordsPerPage) + 1);
}
// no else required
Allthe integer math solutions are going to be more efficient than anyof the floating point solutions.
所有整数数学解决方案都将比任何浮点解决方案更有效。
回答by flux
Alternative to remove branching in testing for zero:
在零测试中删除分支的替代方法:
int pageCount = (records + recordsPerPage - 1) / recordsPerPage * (records != 0);
Not sure if this will work in C#, should do in C/C++.
不确定这是否适用于 C#,应该适用于 C/C++。
回答by Jeremy Hadfied
A generic method, whose result you can iterate over may be of interest:
您可以迭代其结果的通用方法可能会引起您的兴趣:
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;
}