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