zoukankan      html  css  js  c++  java
  • 华为机试-求解立方根

    题目描述

    •计算一个数字的立方根,不使用库函数

    详细描述:

    •接口说明

    原型:

    public static double getCubeRoot(double input)

    输入:double 待求解参数

    返回值:double  输入参数的立方根

    输入描述:

    待求解参数 double类型

    输出描述:

    输入参数的立方根 也是double类型

    示例1

    输入

    216
    

    输出

    6.0
    1. import java.util.Scanner;  
    2.   
    3. /** 
    4.  * 求立方根 牛顿迭代法。设f(x)=x3-y, 求f(x)=0时的解x,即为y的立方根。 
    5.  * 根据牛顿迭代思想,xn+1=xn-f(xn)/f'(xn)即x=x-(x3-y)/(3*x2)=(2*x+y/x/x)/3; 
    6.  *  
    7.  *  
    8.  * @author LiJian 
    9.  * 
    10.  */  
    11. public class Main {  
    12.   
    13.     public static void main(String[] args) {  
    14.   
    15.         Scanner scanner = new Scanner(System.in);  
    16.         char c;  
    17.         while (scanner.hasNext()) {  
    18.             double d = scanner.nextDouble();  
    19.             double result = getCubeRoot(d);  
    20.             System.out.println(String.format("%.1f", result));  
    21.         }  
    22.   
    23.     }  
    24.   
    25.     private static double getCubeRoot(double d) {  
    26.         if (d == 0) {  
    27.             return 0;  
    28.         }  
    29.         double x;  
    30.         for (x = 1.0; Math.abs(x * x * x - d) > 1e-7; x = (2 * x + d / x / x) / 3)  
    31.             ;  
    32.         return x;  
    33.     }  
    34.   
    35. }  
  • 相关阅读:
    (网页)中的简单的遮罩层
    (后端)shiro:Wildcard string cannot be null or empty. Make sure permission strings are properly formatted.
    (网页)jQuery的时间datetime控件在AngularJs中使用实例
    Maven Myeclipse 搭建项目
    MyBatis 环境搭建 (一)
    java 常用方法
    XML 基础
    JS BOM
    js 事件
    js 的使用原则
  • 原文地址:https://www.cnblogs.com/wwjldm/p/7111224.html
Copyright © 2011-2022 走看看