求一个正整数X的平方根Y,立方根Z。
求平方根和立方根我们一般用牛顿迭代法,下面是对应的公式。
平方根迭代公式a(n+1)=(a(n)+Y/a(n))/2,其中Y为待求平方根。
立方根迭代公式a(n+1)={2a(n)+Z/{[a(n)]^2}}/3,其中Z为待求平方根。
java
import java.util.Scanner;
public class cubeSquare {
public double sqrt_root(double a, double x0) {
double x1, y;
x1 = (x0 + a / x0) / 2.0;
if (Math.abs(x1 - x0) >= 0.00001)
y = sqrt_root(a, x1);
else
y = x1;
return y;
}
public double cube_root(double a, double x0) {
double x1, y;
x1 = (2 * x0 + a / (x0 * x0)) / 3.0;
if (Math.abs(x1 - x0) >= 0.00001)
y = cube_root(a, x1);
else
y = x1;
return y;
}
public static void main(String[] args) {
cubeSquare cs = new cubeSquare();
Scanner s = new Scanner(System.in);
double x = s.nextDouble();
System.out.println(cs.sqrt_root(x, 1.0) + ":" + cs.cube_root(x, 1.0));
}
}
#include <math.h>
#include <stdio.h>
double sqrt_root(double a,double x0)
{
double x1,y;
x1=(x0+a/x0)/2.0;
if(fabs(x1-x0)>=0.00001)
y=sqrt_root(a,x1);
else
y=x1;
return y;
}
double cube_root(double a,double x0)
{
double x1,y;
x1=(2*x0+a/(x0*x0))/3.0;
if(fabs(x1-x0)>=0.00001)
y=cube_root(a,x1);
else
y=x1;
return y;
}
int main()
{
double x;
printf("Enter x: ");
scanf("%lf",&x);
printf("The square root of %lf is %f \n",x, sqrt_root(x,1.0));
printf("The cube root of %lf is %f \n",x, cube_root(x,1.0));
return 0;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-03 14:46:32