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-13  โปรแกรมหารากที่สองของจำนวนจริง (ใช้ตัวแปร x0 กับ x1) รุ่นปรับปรุง
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, x1;
    x1 = (x0 + a/x0) / 2.0;
    x0 = (x1 + a/x1) / 2.0;
    x1 = (x0 + a/x0) / 2.0;
    x0 = (x1 + a/x1) / 2.0;
    System.out.println("รากที่สองของ " + a + " = " + x0);
  }
}
©2009 S.Prasitjutrakul