求立方根
2021-02-20 本文已影响0人
simon_kin
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.DecimalFormat;
public class Main {
public static void main(String[] args) throws Exception{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str;
while ((str = br.readLine())!=null) {
double input = Double.parseDouble(str);
DecimalFormat df = new DecimalFormat("#,#0.0");
System.out.printf(df.format(getCubeRoot(input)));
}
}
public static double getCubeRoot(double input) {
/*在这里实现功能*/
if (input == 0) {
return 0;
}
double x0, x1;
x0 = input;
x1 = (2*x0 + input/x0/x0)/3;//利用迭代法求解
while (Math.abs(x1 - x0) > 0.000001) {
x0 = x1;
x1 = (2*x0 + input/x0/x0)/3;
}
return x1;
}
}
/*
功能: 计算一个数字的四次方根
输入:double input 待求解参数
返回值:double 输入参数的四次方根
*/
public static double getFour(double input) {
/*在这里实现功能*/
if (input == 0) {
return 0;
}
double x0, x1;
x0 = input;
x1 = (3*x0 + input/x0/x0/x0) / 4;
while (Math.abs(x1 - x0) > 0.000001) {
x0 = x1;
x1 = (3*x0 + input/x0/x0/x0) / 4;
}
return x1;
}