24h購物| | PChome| 登入
2012-01-19 14:10:33| 人氣1,091| 回應0 | 上一篇 | 下一篇

[JAVA][作業練習] Lab1

推薦 0 收藏 0 轉貼0 訂閱站台

/**
 *
 * @author Shiang-Yun Yang
The Babylonian algorithm to compute the square root of a number n is as follows:
1.Make a guess at the answer (you can pick n/2 as your initial guess)
2.Compute r = n /guess
3.Set guess = (guess + r) / 2
4.Go back to step 2 for as many iterations as necessary. The more you repeat
  steps 2 and 3, the closer guess will become to the square root of n.

Write a program that inputs an integer for n, iterates through the Babylonian
algorithm until the value of guess is the same as the value of Math.sqrt(n) to
the fifth decimal place. For each iteration, print out the value of guess and
the difference between guess and Math.sqrt(n) as double to six decimal places.
At the end of your program, print out the number of guesses as an int and the
value of guess as a double to five decimal places.

 */
import java.util.Scanner;

public class Babylonian {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        System.out.println("Student ID: 4100056008, Author: Shiang-Yun Yang, HW01");
        Scanner cin = new Scanner(System.in);
        int n;
        System.out.print("Input a number, n = ");
        while(cin.hasNext()) {
            n = cin.nextInt();
            double guess, r, sqr_n;
            int index = 0;
            sqr_n = Math.sqrt(n);
            guess = (double)n/2.0;
            while(true) {
                System.out.printf("[%02d]: Guess = %16.6f, \tDifference = %16.6f\n", index, guess, Math.abs(guess-sqr_n));
                if(Math.abs(guess*guess-n) < 0.00001)   break;
                r = n/guess;
                guess = (guess+r)/2.0;
                index++;
            }
            System.out.printf("The number of guesses = %d, guess = %f\n", index, guess);
            System.out.println("==============================================================");
            System.out.print("Input a number, n = ");
                    
        }
    }
}

台長: Morris
人氣(1,091) | 回應(0)| 推薦 (0)| 收藏 (0)| 轉寄
全站分類: 不分類 | 個人分類: [學習]Java |
此分類下一篇:[JAVA][作業練習] Lab2
此分類上一篇:[JAVA][作業練習] Lab3

是 (若未登入"個人新聞台帳號"則看不到回覆唷!)
* 請輸入識別碼:
請輸入圖片中算式的結果(可能為0) 
(有*為必填)
TOP
詳全文