Integer Division Yields Surprising Zero in Double Variable
In attempting to calculate a simple division (3/5), you may encounter unexpected results. Despite storing the result in a double-precision variable, the outcome may erratically appear as zero. To unravel this mystery, let's investigate the underlying mechanism:
In the provided code snippet, both the dividend (3) and divisor (5) are integers. By default, C interprets this division as integer division, which rounds down the result and discards the fractional part. In this case, 3 divided by 5 yields 0, as anticipated in integer division.
To rectify this issue and obtain the desired floating-point division, we need to ensure that at least one of the operands is represented as a real number. This can be achieved by appending ".0" to either the divisor or dividend:
double f = 3.0 / 5; // Explicitly making the dividend a real number // or double f = 3 / 5.0; // Explicitly making the divisor a real number
By converting one of the operands to a real number, we force the compiler to perform floating-point division. This ensures that the fractional part is preserved, and the correct result (0.6 in this case) is stored in the f variable.
The above is the detailed content of Why Does Integer Division in C Result in Zero When Stored in a Double Variable?. For more information, please follow other related articles on the PHP Chinese website!