为什么C#Math.Ceiling向下舍入?

M K*_* II 9 c# math

我有一个艰难的一天,但有些事情没有正确加起来.

在我的C#代码中,我有这个:

Math.Ceiling((decimal)(this.TotalRecordCount / this.PageSize))
Run Code Online (Sandbox Code Playgroud)

其中(int)TotalRecordCount= 12和(int)PageSize= 5.我得到的结果是2.
(两个值都是int值.)

根据我的计算,12/5 = 2.4.我以为Math.Ceiling会一直围着,在这种情况下,给我3?

PS,如果我这样做:

Math.Ceiling(this.TotalRecordCount / this.PageSize)
Run Code Online (Sandbox Code Playgroud)

我收到消息:

Math.Ceiling(this.TotalRecordCount/this.PageSize)
以下方法或属性之间的调用不明确:
'System.Math.Ceiling(decimal)'和'System.Math.Ceiling(double)'

das*_*ght 20

您会看到"向下舍入",因为截断发生在到达之前Math.Ceiling.

当你这样做

(this.TotalRecordCount / this.PageSize)
Run Code Online (Sandbox Code Playgroud)

它是一个整数除法,其结果是截断的int; 把它投入是为时已晚decimal.

要解决这个问题,请在分裂前进行:

Math.Ceiling(((decimal)this.TotalRecordCount / this.PageSize))
Run Code Online (Sandbox Code Playgroud)


Ill*_*ack 7

因为TotalRecordCountPageSize是int,而int division向下舍入.您必须将至少一个操作数转换为十进制才能使用十进制除法:

Math.Ceiling((decimal)this.TotalRecordCount / this.PageSize));
Run Code Online (Sandbox Code Playgroud)