为什么Convert.ToInt32(1.0 / 0.00004)!=(Int32)在(1.0 / 0.00004) [英] Why Convert.ToInt32(1.0/0.00004) != (Int32)(1.0/0.00004)

查看:236
本文介绍了为什么Convert.ToInt32(1.0 / 0.00004)!=(Int32)在(1.0 / 0.00004)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么这个code http://ideone.com/YRcICG

Why this code http://ideone.com/YRcICG

void Main()
{   
    double a = 0.00004;
    Int32 castToInt = (Int32)(1.0/a);
    Int32 convertToInt = Convert.ToInt32(1.0/a);

    Console.WriteLine("{0} {1:F9} {2:F9}", castToInt == convertToInt, castToInt, convertToInt);

    Console.WriteLine((((int)(1.0/(1.0/25000))) == 24999));
}

结果

假24999,000000000 25000,000000000
  真

False 24999,000000000 25000,000000000
True

在CLR上下文/ C#实现

in context of CLR/C# implementation

推荐答案

诀窍在于方式的双重重新presented左右(1.0 / A)将被重新psented通过以下方式$ P $

The trick lies in the way the double is represented so (1.0/a) will be represented in the following way:

(1.0 / A)= 24999.99999999999636202119290828704833984375。

(1.0/a) = 24999.99999999999636202119290828704833984375.

当你使用CAST你得到这个数字的只有前半部分,而转换方法的工作方式不一样,这里是code为转换方法:

When you use cast you get only the first part of this number, while the convert Method works in a different way, here is the code for the Convert method:

public static int ToInt32(double value)
{
    if (value >= 0.0)
    {
        if (value < 2147483647.5)
        {
            int num = (int)value;
            double num2 = value - (double)num;
            if (num2 > 0.5 || (num2 == 0.5 && (num & 1) != 0))
            {
                num++;
            }
            return num;
        }
    }
    else
    {
        if (value >= -2147483648.5)
        {
            int num3 = (int)value;
            double num4 = value - (double)num3;
            if (num4 < -0.5 || (num4 == -0.5 && (num3 & 1) != 0))
            {
                num3--;
            }
            return num3;
        }
    }
    throw new OverflowException(Environment.GetResourceString("Overflow_Int32"));
}

正如你可以看到有一个if语句来检查铸造的价值和原双之间的差异,在您的例子是:

As you can see there is an if statement that checks the difference between casted value and original double, in your example it is:

int num = (int)value;
double num2 = value - (double)num;

24999.99999999999636202119290828704833984375 - 24999 > 0.5

,所以你得到的增量。

, hence you get the increment.

这篇关于为什么Convert.ToInt32(1.0 / 0.00004)!=(Int32)在(1.0 / 0.00004)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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