在 std::floor 之后转换为 int 是否能保证正确的结果?

发布于 2024-07-14 08:56:31 字数 341 浏览 7 评论 0原文

我想要一个带有语法的 floor 函数,

int floor(double x);

std::floor 返回一个 double。 保证

static_cast <int> (std::floor(x));

给我正确的整数,或者我可能会遇到相差一的问题吗? 这似乎有效,但我想确定一下。

对于奖励积分,为什么 std::floor 首先返回 double

I'd like a floor function with the syntax

int floor(double x);

but std::floor returns a double. Is

static_cast <int> (std::floor(x));

guaranteed to give me the correct integer, or could I have an off-by-one problem? It seems to work, but I'd like to know for sure.

For bonus points, why the heck does std::floor return a double in the first place?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

烛影斜 2024-07-21 08:56:31

double 的范围远大于 32 或 64 位整数的范围,这就是 std::floor 返回 double 的原因。 只要在适当的范围内,转换为 int 应该没问题 - 但请注意,double 无法准确表示所有 64 位整数,因此您也可能会结束当超出 double 的准确度(即两个连续双精度值之间的差异大于 1)时,就会出现错误。

The range of double is way greater than the range of 32 or 64 bit integers, which is why std::floor returns a double. Casting to int should be fine so long as it's within the appropriate range - but be aware that a double can't represent all 64 bit integers exactly, so you may also end up with errors when you go beyond the point at which the accuracy of double is such that the difference between two consecutive doubles is greater than 1.

西瓜 2024-07-21 08:56:31
static_cast <int> (std::floor(x));

几乎可以满足您的要求,是的。 它为您提供最接近的整数,四舍五入到无穷大。 至少只要您的输入在整数可表示的范围内。
我不确定你所说的“添加 .5 之类的”是什么意思,但它不会产生相同的效果

并且 std::floor 返回一个双精度值,因为这是最通用的。 有时您可能想要对浮点型或双精度型进行四舍五入,但保留类型。 也就是说,将 1.3f 舍入到 1.0f,而不是 1。

如果 std::floor 返回 int,则很难做到这一点。 (或者至少你会有额外的不必要的演员在那里减慢速度)。

如果 Floor 只执行舍入本身,而不更改类型,则可以在需要时将其转换为 int 。

另一个原因是双精度数的范围远远大于整数的范围。 可能无法将所有双精度数舍入为整数。

static_cast <int> (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.

a√萤火虫的光℡ 2024-07-21 08:56:31

C++ 标准规定 (4.9.1):

“浮点类型的右值可以转换为整数类型的右值。转换会截断;即,小数部分被丢弃。如果截断的值,则行为未定义无法在目标类型中表示”。

因此,如果要将 double 转换为 int,该数字在 int 范围内,并且所需的向上舍入为零,那么只需将数字转换为 int 就足够了:

(int)x;

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;

旧梦荧光笔 2024-07-21 08:56:31

如果您想处理各种数字条件并希望以受控方式处理不同类型的转换,那么也许您应该查看 Boost.NumericConversion。 该库允许处理奇怪的情况(例如超出范围、舍入、范围等),

以下是文档中的示例:

#include <cassert>
#include <boost/numeric/conversion/converter.hpp>

int main() {

    typedef boost::numeric::converter<int,double> Double2Int ;

    int x = Double2Int::convert(2.0);
    assert ( x == 2 );

    int y = Double2Int()(3.14); // As a function object.
    assert ( y == 3 ) ; // The default rounding is trunc.

    try
    {
        double m = boost::numeric::bounds<double>::highest();
        int z = Double2Int::convert(m); // By default throws positive_overflow()
    }
    catch ( boost::numeric::positive_overflow const& )
    {
    }

    return 0;
}

If you want to deal with various numeric conditions and want to handle different types of conversions in a controlled way, then maybe you should look at the Boost.NumericConversion. This library allows to handle weird cases (like out-of-range, rounding, ranges, etc.)

Here is the example from the documentation:

#include <cassert>
#include <boost/numeric/conversion/converter.hpp>

int main() {

    typedef boost::numeric::converter<int,double> Double2Int ;

    int x = Double2Int::convert(2.0);
    assert ( x == 2 );

    int y = Double2Int()(3.14); // As a function object.
    assert ( y == 3 ) ; // The default rounding is trunc.

    try
    {
        double m = boost::numeric::bounds<double>::highest();
        int z = Double2Int::convert(m); // By default throws positive_overflow()
    }
    catch ( boost::numeric::positive_overflow const& )
    {
    }

    return 0;
}

大多数标准数学库使用双精度数,但也提供浮点版本。 如果您不想使用双精度数,则 std::floorf() 是 std::floor() 的单精度版本。

编辑:我删除了之前答案的一部分。 我曾说过,当转换为 int 时,下限是多余的,但我忘记了这只适用于正浮点数。

Most of the standard math library uses doubles but provides float versions as well. std::floorf() is the single precision version of std::floor() if you'd prefer not to use doubles.

Edit: I've removed part of my previous answer. I had stated that the floor was redundant when casting to int, but I forgot that this is only true for positive floating point numbers.

孤独难免 2024-07-21 08:56:31

您可以考虑使用 std::llround(std::floor(x)) 作为长范围内的双打。

You may consider std::llround(std::floor(x)) for doubles in the long long range.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文