如果浮动首次保存到变量,浮动乘法的转换结果会产生不同的结果吗?

时间:2016-08-08 22:56:10

标签: c# casting precision floating-accuracy

这里的代码很简单,但我不了解结果:

float percent = 0.69f;
int firstInt = (int)(percent*100f);

float tempFloat = percent*100f;
int secondInt = (int)tempFloat;

Debug.Log(firstInt + " " + secondInt);

为什么firstInt 68但secondInt是69?

1 个答案:

答案 0 :(得分:1)

看起来编译器已经计算出

的值
percent*100f

表达式使用双数学,并优化了计算。当中间结果保存在float变量中时,不允许这样做。

由于.69在float或double中没有非精确表示,因此两个表示" land"在int的不同侧:double略高于,而float略低于.69的实际值。