2016-03-21 45 views
2

我想獲得在數字的0.000001範圍內舍入的數字的平方根。例如10的sqrt = 3.1622766 .....用雙。我有,但得到舍入爲3.162267是我遇到的問題。我必須使用循環,不能使用類。謝謝賈裏德得到一個數字來循環使用循環而不是Java中的類

import java.util.Scanner; 

public class squareRoot { 
    public static void main(String[] args) { 
     Scanner kb = new Scanner(System.in); 
     System.out.println("Please enter a non-negative integer."); 
     int myInt = kb.nextInt(); 
     { 
      double testNum; 
      double squareRoot = myInt/2; 
      do { 
       testNum = squareRoot; 
       squareRoot = (testNum + (myInt/testNum))/2; 
      } 
      while (squareRoot - (testNum * testNum) > .000001); 
      System.out.println("\nThe square root of " + myInt + " is " + squareRoot); 
     } 
    } 
} 
+0

哇哦,這些缺口是真的* *混亂。 – Andreas

回答

0

的問題是,使用這種算法,有誤差對最後一個數字的元素,所以你可以增加顯著數字的號碼,然後輪所需的數字:

double myDouble = kb.nextDouble(); 
{ 
    double testNum; 
    double squareRoot = myInt/2; 
    do 
    { 
     testNum=squareRoot; 
     squareRoot = (testNum + (myInt/testNum))/2; 
    } 
    while(Math.abs(myDouble - (testNum * testNum)) > .00000001);//←decrease the error here 

    //round squareRoot down to the num of decimals you want   

    System.out.println("\nThe square root of " + myDouble + " is " + squareRoot); 
    } 
} 
0

您可以編寫自己的round()方法,並使用它,而不是建立在Java類:

private static double round(double number, int places){ 
    double result; 
    if(number == (int) number){ 
     return number; 
    } 
    result = (int) number; 
    int multiplier = 1; 
    for(int i = 0 ; i < places ; i++){ 
     multiplier*= 10; 
    } 
    double fraction = number - (int)number; 
    result = result + ((int)(multiplier * fraction))*1.0/multiplier; 
    return result; 
} 

public static void main(String[] args) { 
    double d = 1.6546213; 
    System.out.println(round(d, 2)); 
} 
相關問題