【发布时间】:2017-03-29 16:07:57
【问题描述】:
我有这个代码。为什么在主程序返回值时会产生-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;
}
这让我很困惑。据我所知,我使用合适的数据类型。
【问题讨论】:
-
-5 * x * x - 2 * x + 1对-1是负数 -
If the base is finite negative and the exponent is finite but not an integer value, it causes a domain error.它在参考页面上说得对。 -
@slawekwin:实际上,负数确实有奇数根(例如,-27 的立方根是 -3)。只有负数的偶数根需要虚数。
-
@JerryCoffin:实际上所有的根都需要虚数:三次根有 2 个虚数和 1 个实数。
-
@AdrianMaire:确实也有复数根(就像正数的复数根一样),但是负数有纯粹的奇数根。所以不,不是所有的根需要虚数。