简体   繁体   English

c#中的整数数学

[英]Integer math in c#

I have a menu of product brands that I want to split over 4 columns. 我有一个产品品牌菜单,我想分成4列。 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#): 因此,如果我有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#中对整数进行数学运算?

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结果为decimal您可以删除其中一个强制转换:

int ItemCount = (int) Math.Ceiling( BrandCount / 4m );

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

A longer alternative with Mod. Mod的更长的选择。

ItemCount = BrandCount / 4;
if (BrandCount%4 > 0) ItemCount++;

Perhaps try something like this ... Assuming BrandCount is an integer. 也许尝试这样的事情......假设BrandCount是一个整数。 You still have the same casts, but it might be clearer: 你仍然有相同的演员,但它可能更清楚:

int ItemCount = (int)(Math.Ceiling(BrandCount / 4m));

I'm not a huge fan of the Convert class, and I avoid it whenever possible. 我不是Convert类的忠实粉丝,我尽可能避免使用它。 It always seems to make my code illegible. 它似乎总是使我的代码难以辨认。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM