9

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

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

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

4

4 回答 4

21

你可以投:

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

此外,因为int/decimal导致 adecimal您可以删除其中一个演员表:

int ItemCount = (int) Math.Ceiling( BrandCount / 4m );
于 2008-10-30T13:39:46.127 回答
11

为什么你甚至使用小数?

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;
}
于 2008-10-30T14:02:53.133 回答
7

Mod的更长选择。

ItemCount = BrandCount / 4;
if (BrandCount%4 > 0) ItemCount++;
于 2008-10-30T13:39:45.550 回答
2

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

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

我不是这门课的忠实粉丝Convert,我尽可能避免它。它似乎总是让我的代码难以辨认。

于 2008-10-30T13:41:35.470 回答