C#中的整数数学
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/250191/
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
Integer math in c#
提问by Ben Mills
I have a menu of product brands that I want to split over 4 columns. So if I have 39 brands, then I want the maximum item count for each column to be 10 (with a single gap in the last column. Here's how I'm calculating the item count for a column (using C#):
我有一个产品品牌菜单,我想将其分成 4 列。因此,如果我有 39 个品牌,那么我希望每列的最大项目数为 10(最后一列中有一个空白。这是我计算列的项目数的方法(使用 C#):
int ItemCount = Convert.ToInt32(Math.Ceiling(Convert.ToDecimal(BrandCount) / 4m));
All that conversion seems really ugly to me. Is there a better way to do math on integers in C#?
在我看来,所有这些转换都非常丑陋。有没有更好的方法在 C# 中对整数进行数学运算?
采纳答案by k?e?m?p? ?
You can cast:
你可以投射:
int ItemCount = (int) Math.Ceiling( (decimal)BrandCount / 4m );
Also, because int
/decimal
results in a decimal
you can remove one of the casts:
另外,因为int
/decimal
结果是 adecimal
您可以删除其中一个演员表:
int ItemCount = (int) Math.Ceiling( BrandCount / 4m );
回答by GavinCattell
A longer alternative with Mod.
一个更长的选择与 Mod。
ItemCount = BrandCount / 4;
if (BrandCount%4 > 0) ItemCount++;
回答by John Rudy
Perhaps try something like this ... Assuming BrandCount
is an integer. You still have the same casts, but it might be clearer:
也许尝试这样的事情......假设BrandCount
是一个整数。你仍然有相同的演员表,但它可能更清楚:
int ItemCount = (int)(Math.Ceiling(BrandCount / 4m));
I'm not a huge fan of the Convert
class, and I avoid it whenever possible. It always seems to make my code illegible.
我不是这Convert
门课的忠实粉丝,我尽可能避免。它似乎总是让我的代码难以辨认。
回答by Motti
Why are you even using a decimal?
你为什么甚至使用小数?
int ItemCount = (BrandCount+3)/4;
The +3
makes sure you round up rather than down:
在+3
肯定让你圆了,而不是下降:
(37+3)/4 == 40/4 == 10
(38+3)/4 == 41/4 == 10
(39+3)/4 == 42/4 == 10
(40+3)/4 == 43/4 == 10
In general:
一般来说:
public uint DivUp(uint num, uint denom)
{
return (num + denom - 1) / denom;
}