2013-06-11 23 views
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) 

哪裏是我的錯誤?希望你能幫助。

+3

這可能會啓發你:http://floating-point-gui.de/ – BlackBear

+0

Thx for回覆 – Sharpnel

回答

0

的答案是:「有太多的位數」在double,圓它,它castfloat存放。

2

除了理解不同的變量存儲類型及其精度外,沒有其他真正的錯誤。我只是回答你的問題,而不是試圖粗魯。

此外,您使用的是intfloatdouble都在同一個方程式,然後鑄造了這一切的decimal。這是非常糟糕的做法,因爲它們都有不同的精度。通常,使用必要的最小存儲類型,並使用相同的類型,除非絕對必要,這需要強制轉換(隱式或顯式)並更改精度。

BlackBear的鏈接非常好。

也看到這些SO答案:
https://stackoverflow.com/a/618542/1002098
https://stackoverflow.com/a/10056298/1002098