Fog*_*zie 8 c# precision casting floating-accuracy
这里的代码是直截了当的,但我不明白结果:
float percent = 0.69f;
int firstInt = (int)(percent*100f);
float tempFloat = percent*100f;
int secondInt = (int)tempFloat;
Debug.Log(firstInt + " " + secondInt);
Run Code Online (Sandbox Code Playgroud)
为什么是firstInt68但是secondInt69?
看起来编译器已经计算出了
percent*100f
Run Code Online (Sandbox Code Playgroud)
使用双重数学表达式,并优化计算。当中间结果保存在浮点变量中时,这是不允许的。
由于 0.69 在 float 或 double 中没有精确的表示,因此这两种表示“落在”int 的不同两侧:double 略高于 0.69 的实际值,而 float 略低于 0.69 的实际值。