why is 1.2 * 30 = 35?
Why does this:
int main(v开发者_StackOverflow社区oid)
{
short w = 30;
return 1.2 * w;
}
return 35?
If you want to get more suitable result, try the following:
return 12*w/10
1.2 * w
is 36.0
. It has the double type meaning it is not represented exactly.
Likely it turns out to be slightly less than 36
, maybe 35.99999
so when you return it the fractional part is discarded and the integer part only is returned. That's how you get 35
.
P.S. All operations with floating point are not precise. You should expect little discrepancies. Also when you compare a floating point value against a fixed value, you mustn't do a direct comparison but do a range comparison.
Wrong: if (value == 36.0) { /* ... */ }
Correct: if (abs (value - 36.0) < 0.0001) { /* ... */ }
It's an issue with binary floating point precision. 1.2
is very slightly less than 1.2, so the result of the multiplication is slightly less than 36.
Because of representation: 1.2 is really something like 1.1999999
Since floating point math could be inexact, use round()
before casting to integer, to get a better result.
#include <math.h>
...
return (int)round(some_real_value);
Don't expect absolutely exact result in floating point operations. Multiplication result may be, for example, 35.9999, which is rounded to 35.
short w = 30; return 1.2 * w;
In return statement first sort value is type cast in double because 1.2 is double type so it will multiply 1.2 * 30.000000 and result become around 35.999999 and function return type is int so decimal part is truncate and it return 35 only.
精彩评论