在Flash中除了错误错误、Flash

2023-09-08 15:37:33 作者:一个人的天黑格外美。

请在新AS3文件在Flash中,粘贴以下code和运行:

Make a new AS3 Document in Flash, paste in the following code and run it:

var a:Number=0;
trace(a)  //  0
a+=0.3;
trace(a)  //  0.3
a+=0.3;
trace(a)  //  0.6
a+=0.3;

trace(a)  //  0.8999999999999999
a+=0.3;
trace(a)  //  1.2
a+=0.3;
trace(a)  //  1.5
a+=0.3;
trace(a)  //  1.8
a+=0.3;
trace(a)  //  2.1
a+=0.3;
          //  ^ This is the output. Notice the inaccuracy starting from 0.9 / 0.89

为什么错误?我只是在做一个普通的高解析度的补充。

Why the error? I'm just doing an ordinary hi resolution addition.

所有的解决方法?

推荐答案

这是一个标准的浮点问题。二进制浮点数字不重复present全方位的十进制数完全准确的,你需要做的线沿线的东西

This is a standard floating point problem. Binary floating point numbers do not represent the full range of decimal numbers with perfect accuracy, you need to do something along the lines of

trace (round (a, 1))

,或者更好的,把它变成一个字符串,并去掉一切都会过去的第一个小数位(自轮的结果也可能不容易再presentable二进制)。

or, better yet, turn it into a string and strip off everything past the first fractional digit (since the result of round may also not be easily representable in binary).

虽然我不知道动作。不过这是一个非常著名的问题,而不是仅限于AS3。

although I don't know ActionScript. Still it's a very well known issue and not limited to AS3.

例如,见http://stackoverflow.com/questions/177506/why-do-i-see-a-double-variable-initialized-to-some-value-like-214-as-2139999961或http://stackoverflow.com/questions/327544/strange-floating-point-behaviour-in-a-java-program或http://stackoverflow.com/questions/249467/what-is-a-simple-example-of-floating-pointrounding-error.

 
精彩推荐
图片推荐