//計算一個數
package demo0527;
import java.io.BufferedReader;
import javax.swing.InputMap;
public class demo07 {
//計算一個數字的立方根呢,不使用庫函數
public static boolean isTest=false;
public static void main(String[] args) {
if (isTest) {
new Main.test();
}else {
BufferedReader br=new BufferedReader(new InputStream(System.in));
String str=null;
do {
str=br.readLine();
if(str!=null) {
double d=new Main.run(str);
String tempD=Double.toString(d);
tempD=tempD.substring(0,4);
int last=Integer.parseInt(tempD.substring(3,4));
if(last>=5) {
d+=0.1;
}
tempD=Double.toString(0,3);
tempD=tempD.substring(0,3);
System.out.println(tempD);
}
}while(str!=null)
}
}
public double run(String str) {
double num=Double.parseDouble(str);
double dis=1.0;
double start=0.1;
for(double i=0;dis>0.0;i+=0.01) {
double temp=i*i*i;
dis=num-temp;
start=i;
}
return start;
}
public void test() {
String test="11";
double d=new Main().run(test);
String tempD=Double.toString(d);
tempD=tempD.substring(0,4);
int last=Integer.parseInt(tempD.substring(3,4));
if(last>=5) {
d+=0.1;
}
tempD=Double.toString(d);
tempD=tempD.substring(0,3);
System.out.println(tempD);
}
}
方法二:
字的立方根呢,不使用庫函數。
牛頓迭代法。設f(x)=x3-y, 求f(x)=0時的解x,即爲y的立方根。
根據牛頓迭代思想,xn+1=xn-f(xn)/f'(xn)即x=x-(x3-y)/(3*x2)=(2*x+y/x/x)/3;
import java.util.*;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
while(sc.hasNext()){
double n = sc.nextDouble();
double e = 0.000001;
double a =n;
double a1 = (2*a+n/a/a)/3;
while(Math.abs(a1*a1*a1-n)>e){
a1 = (2*a1+n/a1/a1)/3;
}
System.out.printf("%.1f",a1);
System.out.println();
}
}
}
二分方法:
public static double getCubeRoot(double input){
double min = 0;
double max = input;
double mid =0;
while((max-min)>0.0001){
mid =(max+min)/2;
if(mid*mid*mid>input){
max = mid;
continue;
}
if(mid*mid*mid<input){
min = mid;
continue;
}
return mid;
}
return max;
}
}
解法1: