函数 returns -nan

Function returns -nan

我有这个代码。为什么在主程序返回值时产生-nan

#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cmath>

using namespace::std;

float f(float x)
{
    float result = -5 * x * x - 2 * x + 1;
    return powf(result, (float)1/(float)3);
}
int main()
{
    cout<<f(-1)<<endl;
    getchar();
    return 0;
}

这让我很困惑。据我所知,我使用合适的数据类型。

cplusplus参考说:

The NaN values are used to identify undefined or non-representable values for floating-point elements, such as the square root of negative numbers or the result of 0/0.

The argument can be used by library implementations to distinguish different NaN values in a implementation-specific manner.

当您用负一调用函数时,底数等于 -2,指数为 1/3(非整数)。

根据 powf 的规范:

pow(base, exponent) returns NaN and raises FE_INVALID if base is finite and negative and exponent is finite and non-integer.

这解释了为什么您的函数返回 NaN。

如果您要计算立方根,我建议您改用 cbrt

正如其他人所提到的,std::pow 无法提供所需的功能。相反,您可以使用 std::cbrt 或简单地这样做:

#include<cstdio>
#include<iostream>
#include<cstdlib>
#include<cmath>

using namespace::std;

float f(float x)
{
    float result = -5 * x * x - 2 * x + 1;
    float intermediate = powf(std::abs(result),(float)1/(float)3);
    if (std::signbit(result))
        return -intermediate; // Negate if 'result' is negative
    return intermediate;
}
int main()
{
    cout<<f(-1)<<endl;
    getchar();
    return 0;
}

您也可以只使用 std::pow 的重载之一,而不是 powf

#include<iostream> // std::cout, std::endl
#include<cstdio>   // getchar
#include<cmath>    // std::pow, std::abs, std::signbit

float f(float x)
{
    float result = -5.0f * x * x - 2.0f * x + 1.0f;
    float intermediate = std::pow(std::abs(result),1.0f/3.0f);
    if (std::signbit(result))
        return -intermediate; // Negate if 'result' is negative
    return intermediate;
}

int main()
{
    std::cout << f(-1) << std::endl;
    getchar();
}

在线here