为什么C#Math.Ceiling向下取整? [英] Why does C# Math.Ceiling round down?

查看:216
本文介绍了为什么C#Math.Ceiling向下取整?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我今天过得很艰难,但是有些事情加起来不正确.

I'm having a rough day, but something is not adding up correctly.

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

In my C# code, I have this:

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

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

Where (int)TotalRecordCount = 12 and (int)PageSize = 5. The result I am getting is 2.
(Both values are int values.)

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

By my calculations, 12 / 5 = 2.4. I thought Math.Ceiling would always round up, and in this case, give me 3?

PS,如果我这样做的话:

PS, if I do this:

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

我收到消息:

Math.Ceiling(this.TotalRecordCount/this.PageSize)
下列方法或属性之间的调用不明确:
"System.Math.Ceiling(十进制)"和"System.Math.Ceiling(双精度)"

Math.Ceiling(this.TotalRecordCount / this.PageSize)
The call is ambiguous between the following methods or properties:
'System.Math.Ceiling(decimal)' and 'System.Math.Ceiling(double)'

推荐答案

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

You see "rounding down" because the truncation happens before reaching Math.Ceiling.

执行此操作

(this.TotalRecordCount / this.PageSize)

它是整数除法,其结果是截断的int;现在将其投射到decimal为时已晚.

It is an integer division, and its result is a truncated int; it is too late to cast it to decimal.

要解决此问题,请在除法之前进行投射:

To fix this problem, cast before the division:

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

这篇关于为什么C#Math.Ceiling向下取整?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆