2. คำนวณ

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.

 
รหัสที่ 2-11  โปรแกรมหารากที่สองของจำนวนจริง
import java.util.Scanner;  
// โปรแกรมหารากที่สองของจำนวนจริงด้วยวิธีของชาวบาบิโลน 
public class SquareRoot {
  public static void main(String[] args) {
    Scanner kb = new Scanner(System.in);
    System.out.print("a = ");
    double a = kb.nextDouble();
    double x0 = 1; // เริ่มที่ค่าใดก็ได้ที่ไม่ใช่ 0
    double x1 = (x0 + a/x0) / 2.0;
    double x2 = (x1 + a/x1) / 2.0;
    double x3 = (x2 + a/x2) / 2.0;
    double x4 = (x3 + a/x3) / 2.0;
    System.out.println("รากที่สองของ " + a + " = " + x4);
  }
}
©2009 S.Prasitjutrakul