在现实世界中,应该存在负数的立方根:
cuberoot(-1)=-1,这意味着(-1)*(-1)*(-1)=-1
或者
cuberoot(-27)=-3,这意味着(-3)*(-3)*(-3)=-27
但是当我使用pow函数计算C中负数的立方根时,我得到nan(不是数字)
double cuber;
cuber=pow((-27.),(1./3.));
printf("cuber=%f\n",cuber);
Run Code Online (Sandbox Code Playgroud)
输出: cuber=nan
有没有办法计算C中负数的立方根?
Ste*_*non 20
7.12.7.1 cbrt功能
概要
#include <math.h>
double cbrt(double x);
float cbrtf(float x);
long double cbrtl(long double x);
Run Code Online (Sandbox Code Playgroud)
描述
该cbrt函数计算的真正的立方根x.
如果您很好奇,pow则不能用于计算多维数据集根,因为三分之一不能表示为浮点数.你实际上要求pow提升-27.0到几乎等于1/3的理性力量; 没有合适的实际结果.
有.记住:x ^(1/3)= - ( - x)^(1/3).所以以下应该这样做:
double cubeRoot(double d) {
if (d < 0.0) {
return -cubeRoot(-d);
}
else {
return pow(d,1.0/3.0);
}
}
Run Code Online (Sandbox Code Playgroud)
写入时没有编译,因此可能存在语法错误.
问候,约斯特