Why do round() and ceil() not return an integer?

前端 未结 2 1668
萌比男神i
萌比男神i 2020-12-15 02:32

Once in a while, I find myself rounding some numbers, and I always have to cast the result to an integer:

int rounded = (int) floor(value);

2条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-15 03:04

    That's because float's range is wider than int's. What would you expect to have if the value returned by these functions did not fit into an int? That would be undefined behaviour and you would be unable to check for that in your program.

提交回复
热议问题