如何解决十进制和双精度之间的数学误差?

时间:2017-03-13 00:52:31

标签: c# .net winforms

return Math.Ceiling((_BytesReceived / _TotalBytesToReceive) * 100);

_BytesReceived是int,_TotalBytesToReceive也是int。

错误是:

  

严重级代码描述项目文件行抑制状态   错误CS0121以下方法或属性之间的调用不明确:'Math.Ceiling(decimal)'和'Math.Ceiling(double)'DownloadMultipleFiles

完整功能:

public int ProgressPercentage
    {
        get
        {
            if (_TotalBytesToReceive > 0)
            {
                return Convert.ToInt32(Math.Ceiling((_BytesReceived / (double)_TotalBytesToReceive) * 100d));
            }
            else
            {
                return -1;
            }
        }
    }

2 个答案:

答案 0 :(得分:1)

也许您应该将所有变量转换为int或您想要的例子:

Convert.Toint32(value); Convert.ToDouble(value);

等等

答案 1 :(得分:0)

您可以尝试:

return (int)Math.Ceiling((double)(
   (double)_BytesReceived / (double)_TotalBytesToReceive * 100.0d
));

或者您更喜欢float

return (int)Math.Ceiling((float)(
   (float)BytesReceived / (float)_TotalBytesToReceive * 100.0f
));

原因是,Math.Ceil超载,接受floatdouble。你的表达式需要转换为目标类型,编译器只想知道它应该转换为什么类型,因为两者都是可能的。

请注意,在使用float时,可能仍然需要在开头添加其他类型转换(没有尝试那个)。