我有一个产品品牌菜单,我想分成4列。因此,如果我有39个品牌,那么我希望每列的最大项目数为10(在最后一列中有一个间隙。这是我如何计算列的项目数(使用C#):

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

所有转换对我来说都很难看。有没有更好的方法在C#中对整数进行数学运算?

有帮助吗?

解决方案

你可以施放:

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

另外,因为 int / decimal 导致 decimal ,你可以删除其中一个强制转换:

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

其他提示

为什么你甚至使用小数?

int ItemCount = (BrandCount+3)/4;

+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

一般来说:

public uint DivUp(uint num, uint denom)
{
    return (num + denom - 1) / denom;
}

使用Mod的更长的替代方案。

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

也许尝试这样的事情......假设 BrandCount 是一个整数。你仍然有相同的演员,但它可能更清楚:

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

我不是 Convert 类的忠实粉丝,我尽可能避免使用它。它似乎总是使我的代码难以辨认。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top