3. ทำซ้ำ ๆ

The Camtasia Studio video content presented here requires JavaScript to be enabled and the latest version of the Macromedia Flash Player. If you are you using a browser with JavaScript disabled please enable it now. Otherwise, please update your version of the free Flash Player by downloading here.

 
รหัสที่ 3-10  โปรแกรมหารากที่สอง ใช้วงวนจนได้คำตอบที่ผิดพลาดไม่เกิน 10-5
import java.util.Scanner;  
// โปรแกรมหารากที่สองของจำนวนจริงด้วยวิธีของชาวบาบิโลน (ผิดพลาดไม่เกิน 0.00001)
public class SquareRoot {
  public static void main(String[] args) {
    Scanner kb = new Scanner(System.in);
    System.out.print("a = ");
    double a = kb.nextDouble();
    double x = 1;
    while (true) {
      x = (x + a/x) / 2.0;
      if ((x*x - a) < 1e-5) break;
    }
    System.out.println("รากที่สองของ " + a + " = " + x);
  }
}
©2009 S.Prasitjutrakul