Does casting to an int after std::floor guarantee the right result?

前端 未结 5 1490
旧巷少年郎
旧巷少年郎 2020-11-30 05:38

I\'d like a floor function with the syntax

int floor(double x);

but std::floor returns a double. Is<

5条回答
  •  隐瞒了意图╮
    2020-11-30 05:53

    The C++ standard says (4.9.1):

    "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".

    So if you are converting a double to an int, the number is within the range of int and the required rounding-up is toward zero, then it is enough to simply cast the number to int:

    (int)x;

提交回复
热议问题