题解 | #求解立方根#

求解立方根

https://www.nowcoder.com/practice/caf35ae421194a1090c22fe223357dca

几个点:

1、输出的精确度与计算的是不一样的,不要混在一起,可能会导致精度失真;

2、将负数转成正数再处理可减少很多麻烦;

3、要注意0~1之间的数,立方根也在0~1之间,二分法时需要注意最高位的值。

public class Main { 
  public static void main(String[] args) {        
	Scanner in = new Scanner(System.in);        
	while (in.hasNextDouble()) {           
	  double ual = in.nextDouble();           
	  StringBuilder sb = new StringBuilder();            
	  if (ual < 0) {                
		sb.append("-");               
		ual = 0 - ual;         
	  }         
	  double low = 0;          
	  double high = ual;            
	  if (ual < 1) {             
		// 0~1之间的数,取于0~1         
		high = 1;           
	  }          
	  // 二分法        
	  double val = calc(ual, low, high);          
	  sb.append(String.format("%.1f", val));          
	  System.out.println(sb);       
	}  
  }    
  private static double calc(double ual, double low, double high) {      
	double cube = (low + high) / 2;     
	double div = ual - cube * cube * cube;        
	if (div > 0.000001) {           
	  return calc(ual, cube, high);       
	} else if (div < -0.000001) {        
	  return calc(ual, low, cube);      
	}       
	return cube;   
  }
}
全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务