Unusual behavior of C# floating point to integer conversion: difference between direct conversion and variable assignment
In C#, developers often encounter a strange behavior when converting the result of a floating point expression to an integer. For example, consider the following code snippet:
<code class="language-csharp">int speed1 = (int)(6.2f * 10); float tmp = 6.2f * 10; int speed2 = (int)tmp;</code>
Intuitively, speed1 and speed2 should have the same value. However, this is not the case: speed1 is equal to 61 and speed2 is equal to 62.
Explanation of differences
The root cause lies in the subtle difference between direct conversion and variable assignment. In the case of speed1, the expression 6.2f * 10 results in a floating point value of 61.999998. When implicitly converted to an integer, this value is truncated to 61.
On the other hand, the variable tmp explicitly stores a floating point value of 61.999998. When explicitly converted to an integer, this value is rounded to the nearest integer, resulting in 62.
Intermediate precision
This difference becomes even more interesting when analyzing the bytecode generated by the compiler. In the first case, the expression 6.2f * 10 becomes the intermediate value directly. In the second case, the compiler stores the result in a floating point variable, creating an intermediate step.
This difference in intermediate storage affects the accuracy of the final result. The compiler allows higher-precision intermediate values to be used, even if the formal type (float) implies otherwise. In some cases where the compiler does this, the result may be truncated to 61, causing the observed difference.
How to avoid this problem
To ensure consistency in these cases, it is recommended to explicitly round floating point expressions before converting to integers, as in the following example:
<code class="language-csharp">int speed3 = (int)Math.Round(6.2f * 10);</code>
The above is the detailed content of Why Do Direct Casts and Variable Assignments of C# Float Expressions Yield Different Integer Results?. For more information, please follow other related articles on the PHP Chinese website!