键盘输入一个实数a,输出它的立方根。请自行设计算法编写程序,不允许调用pow函数。
假设a的立方根为x,则x3=a,问题转化求一元高次方程x3-a=0的解。
牛顿法,可以百度一下
#include
typedef enum Boolean{FALSE, TRUE}Boolean;
/*
函数: double CubeRoot(double)
功能: 求解一个数的立方根
算法: 牛顿法
使用: 输入一个实数,输出输入实数的立方根
/
double CubeRoot(const double stuff)
{
const double precision = 0.00001; / 精度 */
double nextX, currentX;
double squareX; /* 当前值 的平方 */
double cubeX; /* 下个解 的立方 */
Boolean flag;
currentX = stuff; /* 初始化当前的值为X */
if (stuff == 0)
{
return stuff;
}
else
{
do
{
squareX = currentX * currentX;
nextX = (2*currentX + stuff/squareX) / 3; /* 牛顿迭代公式 */
cubeX = nextX*nextX*nextX;
if ( (cubeX - stuff < precision) && (cubeX - stuff > -precision))
{
flag = TRUE;
}
else
{
flag = FALSE;
currentX = nextX;
}
}while(flag == FALSE);
}
return nextX;
}
int main()
{
double a;
printf("输入一个实数值: ");
scanf("%lf",&a);
printf("%.3lf的立方根= %.3lf\n",a,CubeRoot(a));
return 0;
}
示例运行结果:
输入一个实数值: 27
27.000的立方根= 3.000
输入一个实数值: 9
9.000的立方根= 2.080
输入一个实数值: 125
125.000的立方根= 5.000
https://zhidao.baidu.com/question/579697654.html
我来个简单的,不一定精准,但很好理解
float x = 0, a = 0;
float calculate(float b,float c)
{
float t = (b+c)/2;
float t2 = t*t*t - a;
if (abs(t2) <= 0.000001f) return b;
else
{
if(t2>0) return calculate(t, b>c?c:b);
else return calculate(t, b>c ? b : c);
}
}
float result(float tmp)
{
if (tmp == 1)
return 1;
else
return calculate(tmp,1);
}
void main()
{
scanf("%f", &a);
float tmp = abs(a);
x = result(tmp);
if (a < 0)
x = 0 - x;
printf("%.3f\n", x);
}