How does Float round when converting it into integer

北战南征 提交于 2019-12-18 06:53:26

问题


If I have

(float)value = 10.50

and do

int new_value = (int)value

what rules will round number?


回答1:


When a finite value of floating type is converted to an integer type, the fractional part is discarded (i.e., the value is truncated toward zero).

So in the case of -10.5, it's converted to -10.

C++11 4.9 Floating-integral conversions [conv.fpint]

An rvalue of a floating point type can be converted to an rvalue of an integer type. The conversion truncates; that is, the fractional part is discarded. The behavior is undefined if the truncated value cannot be represented in the destination type. [ Note: If the destination type is bool, see 4.12. —end note ]




回答2:


The rule is quite simple: the number simply gets truncated to its integral part, in this case, to 10. The fractional part gets dropped entirely. The same applies to negative numbers: -10.5 would be converted to -10.




回答3:


When converted to integers, the fractional part of the float is dropped, meaning the float 10.5 will be converted to the integer 10, and the float -10.5 will be converted to the integer -10.



来源:https://stackoverflow.com/questions/19079290/how-does-float-round-when-converting-it-into-integer

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