为什么C#Math.Ceiling向下舍入?
我有一个艰难的一天,但有些东西没有正确加起来。
在我的C#代码中,我有这个:
Math.Ceiling((decimal)(this.TotalRecordCount / this.PageSize))
Where (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)’
您会看到“向下舍入”,因为截断在到达Math.Ceiling
之前发生。
当你这样做
(this.TotalRecordCount / this.PageSize)
它是一个整数除法,其结果是截断的int
; 将其转换为decimal
为时已晚。
要解决这个问题,请在分裂前施放:
Math.Ceiling(((decimal)this.TotalRecordCount / this.PageSize))
因为TotalRecordCount和PageSize是int,而int division向下舍入 。 您必须将至少一个操作数转换为十进制才能使用十进制除法:
Math.Ceiling((decimal)this.TotalRecordCount / this.PageSize));