why is 1.2 * 30 = 35?

穿精又带淫゛_ 提交于 2019-12-12 13:55:06

问题


Why does this:

int main(void)
{
    short w = 30;
    return  1.2 * w;
}

return 35?


回答1:


If you want to get more suitable result, try the following:

return 12*w/10



回答2:


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) { /* ... */ }




回答3:


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.




回答4:


Because of representation: 1.2 is really something like 1.1999999




回答5:


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);



回答6:


Don't expect absolutely exact result in floating point operations. Multiplication result may be, for example, 35.9999, which is rounded to 35.




回答7:


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.



来源:https://stackoverflow.com/questions/3811355/why-is-1-2-30-35

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!