java不使用库函数实现求立方根
题目:计算一个数字的立方根,不使用库函数
详细描述:
接口说明
原型:
public static double getCubeRoot(double input)
输入:double 待求解参数
返回值:double 输入参数的立方根,保留一位小数
立方根求法
使用二分查找算法:通过多次循环求出符合精度要求的根值
public static double kaiGen(double input){
double min = 0;
double max = input;
double mid = 0;
while((max - min) > 0.001){ //精度
mid = (max + min) / 2;
if((mid * mid * mid) > input){
max = mid;
}
else if((mid * mid * mid) < input){
min = mid;
}
else{
return mid;
}
}
return max; //当输入为0时直接返回
}
数字格式化
- 关于数字格式化,我的理解是修改数字的显示格式,例如1234 ——> 1,234.000
- 数字格式有哪些:
# 代表任意数字
, 代表千分位
. 代表小数点
0 表示不够时补零 - decimalFormat.format()输出结果为字符串
import java.text.DecimalFormat;
DecimalFormat decimalFormat = new DecimalFormat("#.0");
System.out.println(decimalFormat.format(kaiGen(input)));
整体:
import java.util.*;
import java.text.DecimalFormat;
public class Main{
public static void main(String[] args){
Scanner sc = new Scanner(System.in);
double input = sc.nextDouble();
DecimalFormat decimalFormat = new DecimalFormat("#.0");
System.out.println(decimalFormat.format(kaiGen(input)));
}
public static double kaiGen(double input){
double min = 0;
double max = input;
double mid = 0;
while((max - min) > 0.001){
mid = (max + min) / 2;
if((mid * mid * mid) > input){
max = mid;
}
else if((mid * mid * mid) < input){
min = mid;
}
else{
return mid;
}
}
return max;
}
}