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

さまざまな変数ストレージの型とその精度を理解していること以外に、実際のエラーはありません。私はあなたの質問に答えているだけで、失礼なことをしようとしているわけではありません。

また、intfloat、およびdoubleすべてを 1 つの方程式で使用し、そのすべてを にキャストしていdecimalます。これらはすべて精度が異なるため、これは非常に悪い習慣です。一般に、必要最小限のストレージ型を使用し、絶対に必要でない限り同じ型を使用します。これには、(暗黙的または明示的に) キャストが必要で、精度が変わります。

BlackBear のリンクは非常に優れています。

これらの SO の回答も参照してください:
https://stackoverflow.com/a/618542/1002098

于 2013-06-11T21:22:21.073 に答える
0

答えは次のとおりです。「桁数が多すぎる数字」を a に格納しdouble、丸めてcasta にしfloatます。

于 2013-06-12T23:51:22.100 に答える