为什么C#中的Math.Ceiling向下取整?

12

我今天过得很糟糕,但是有些事情在我的代码里面不正确。

在我的C#代码中,我有这样一个东西:

Math.Ceiling((decimal)(this.TotalRecordCount / this.PageSize))

(int)TotalRecordCount = 12并且(int)PageSize = 5时,我得到的结果是2。
(两个值都是int类型。)

根据我的计算,12/5=2.4。我以为Math.Ceiling总是会四舍五入,而在这种情况下会给我3?

PS,如果我这样做:

Math.Ceiling(this.TotalRecordCount / this.PageSize)

我收到了这条消息:

Math.Ceiling(this.TotalRecordCount / this.PageSize)
此调用存在以下方法或属性之间的歧义:
'System.Math.Ceiling(decimal)' 和 'System.Math.Ceiling(double)'

2个回答

30

因为在达到 Math.Ceiling 之前截断已经发生,所以你会看到 "向下取整"。

当你这样做时

(this.TotalRecordCount / this.PageSize)

这是一种整数除法,其结果为截断的 int;将其转换为 decimal 已经太晚。

要解决此问题,请在除法之前进行类型转换:

Math.Ceiling(((decimal)this.TotalRecordCount / this.PageSize))

11

由于TotalRecordCountPageSize都是整数,而整数除法向下取整。您必须将至少一个操作数转换为十进制以使用十进制除法:

Math.Ceiling((decimal)this.TotalRecordCount / this.PageSize));

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接