我有这段代码;
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#在编译时执行这个数学运算并输出不同?
这两个代码有什么区别?为什么我决定使用变量结果正在改变?
答案 0 :(得分:2)
因为编译器欺骗了你。编译器足够智能,可以进行一些数学计算,因此它不需要在运行时执行此操作,这将毫无意义。表达式100 * .01f
在编译器中计算,而不需要浮点数的精度,breaks you up on run-time。
要证明这一点,请尝试将static test
设为const
。你会看到编译器能够在编译时为你做数学运算。它与首先写入变量没有任何关系,就像你的样本一样。运行时与编译时是。