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-11  โปรแกรมหาค่าเฉลี่ยจากข้อมูล 4 จำนวน
import java.util.Scanner;
// โปรแกรมหาค่าเฉลี่ยจากข้อมูล 4 จำนวน 
public class Average1 {
  public static void main(String[] args) {
    Scanner kb = new Scanner(System.in);
    double sum = 0; // sum เก็บผลบวกชุดข้อมูล 
    int k = 0;      // k ไว้นับจำนวนรอบ 
    while (true) {
      if (k >= 4) break;
      System.out.print("จำนวนที่ " + (k+1) + " = ");
      sum += kb.nextDouble(); // อ่านข้อมูล แล้วเพิ่มเข้าผลรวม 
      k++;
    }
    System.out.println("ค่าเฉลี่ย = " + (sum / 4));
  }
}
©2009 S.Prasitjutrakul