0

这里发生了非常奇怪的事情:

float theFloat = 10f * 0.5f * 0.0502913967f;

//result is 0.2514569835f
//but a float's precision is only 7digits so it's false.    
//I corrected it, rounded at 6digits, result is 0.251457f

float theFloat = (float)Math.Round((decimal)(10f * 0.5f * 0.0502913967f), 6);

没关系,但是当我将它与另一个浮点数一起使用时:

Vector2 theVector2 = new Vector2(16302.51f, 0f);
theVector2.X += theFloat;

//means : (16302.51 + 0.251457) = 16302.761457
//but when I check the var the result is : 16302.7607
//so I don't get it...
//also, if theVector2 is 200f more than the previous example (=16502.51f, 0f),
//result is 16502.7617 (200.001f more than previous example's result)

我的错误在哪里?希望你能帮忙。

4

2 回答 2

2

除了您对不同变量存储类型及其精度的理解之外,没有真正的错误。我只是在回答你的问题,而不是试图粗鲁。

此外,您在一个方程式中使用int,floatdoubleall ,然后将所有这些转换为decimal. 这是非常糟糕的做法,因为它们都有不同的精度。一般来说,使用最小的存储类型,除非绝对必要,否则使用相同的类型,这需要强制转换(隐式或显式)并改变精度。

BlackBear 的链接非常好。

另请参阅这些 SO 答案:
https ://stackoverflow.com/a/618542/1002098
https://stackoverflow.com/a/10056298/1002098

于 2013-06-11T21:22:21.073 回答
0

答案是:将“数字过多的数字”存储在 a 中double,将其四舍五入并将cast其存储在 a 中float

于 2013-06-12T23:51:22.100 回答