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

前端 未结 5 1487
旧巷少年郎
旧巷少年郎 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:57

    static_cast  (std::floor(x));
    

    does pretty much what you want, yes. It gives you the nearest integer, rounded towards -infinity. At least as long as your input is in the range representable by ints. I'm not sure what you mean by 'adding .5 and whatnot, but it won't have the same effect

    And std::floor returns a double because that's the most general. Sometimes you might want to round off a float or double, but preserve the type. That is, round 1.3f to 1.0f, rather than to 1.

    That'd be hard to do if std::floor returned an int. (or at least you'd have an extra unnecessary cast in there slowing things down).

    If floor only performs the rounding itself, without changing the type, you can cast that to int if/when you need to.

    Another reason is that the range of doubles is far greater than that of ints. It may not be possible to round all doubles to ints.

提交回复
热议问题