可变动作奇怪(如浮点)

时间:2016-05-04 09:19:20

标签: c# point floating

我有这段代码;

 static int test = 100;
        static int Test
        {
            get
            {
                return (int)(test * 0.01f);
            }
        }

输出为:0

但是这段代码会返回不同的

static int test = 100;
    static int Test
    {
        get
        {
            var y = (test * 0.01f);
            return (int)y;
        }
    }

输出为:1

我也有这段代码

  static int test = 100;
    static int Test
    {
        get
        {
            return (int)(100 * 0.01f);
        }
    }

输出为:1

我看看IL输出,我不明白为什么C#在编译时执行这个数学运算并输出不同? enter image description here

这两个代码有什么区别?为什么我决定使用变量结果正在改变?

1 个答案:

答案 0 :(得分:2)

因为编译器欺骗了你。编译器足够智能,可以进行一些数学计算,因此它不需要在运行时执行此操作,这将毫无意义。表达式100 * .01f在编译器中计算,而不需要浮点数的精度,breaks you up on run-time

要证明这一点,请尝试将static test设为const。你会看到编译器能够在编译时为你做数学运算。它与首先写入变量没有任何关系,就像你的样本一样。运行时与编译时是。