4. เลือกปฏิบัติ

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.

 
รหัสที่ 4-6  โปรแกรมหาจำนวนตรรกยะ n/d ที่มีค่าต่างจาก pi น้อยกว่า 10-6
public class ApproxPi {
  public static void main(String[] args) {
    double n = 22, d = 7;
    double pi = 3.141592653589793;  
    double diff, diff1, diff2;
    while (true) {
      diff1 = Math.abs(pi - (n + 1) / d);  
      diff2 = Math.abs(pi - n / (d + 1));  
      if (diff1 < diff2) {
        n = n + 1;     
        diff = diff1;
      } else {
        d = d + 1;     
        diff = diff2;
      }
      if (diff < 1e-6) break;  
    }
    System.out.println(n + "/" + d + " = " + (n/d));
  }
}
©2009 S.Prasitjutrakul