English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
所有分類

(This is a version of an exercise from Chapter2).The Babylonian algorithm to computethe 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/guess3. Set guess =(guess=r)/24. Go back to step 2 until the last two guess values are the same.程式問題 麻煩高手幫忙解答

2006-06-01 18:19:22 · 1 個解答 · 發問者 23歲九局下半 4 in 社會與文化 語言

1 個解答

由於我對步驟 3 有些疑慮,找了一下 Babylonian algorithm 的解釋,因此在翻譯方面與原文有些出入,請見諒。巴比倫演算法是用於計算數字 n 的平方根,方法如下:1. 產生一個變數 guess 當作答案 (你可以把 n/2 當作第一個猜測的數值)2. 計算 r = n / guess3. 讓 guess = (guess+r) / 24. 如果有需要重複第二步驟,重複更多次的步驟二和三可以讓 guess 更接近 n 的平方根以下是我的做法,請參考。import java.io.*;public class Babylonian { public static void main(String[] args) throws Exception {  BufferedReader br = new BufferedReader(new InputStreamReader(System.in));  System.out.print("Input a non-negative number: ");  int n = Integer.parseInt(br.readLine());    double guess = n / 2;  double r = 0.0D;  for (int i = 0; i < 10000; i++) {   r = n / guess;   guess = (guess + r) / 2;  }      System.out.println("After 10,000 times calculation, the square root of " + n + " is " + r); }}

2006-06-02 15:06:06 · answer #1 · answered by ? 7 · 0 0

fedest.com, questions and answers