- 印出表格中內容,求每日平均溫度、各時段平均溫度
public class P628 { public static void main(String[] args) { // 可利用二維矩陣來印出表格內容文字 double[][] a = { { 18.2, 17.3, 15.0, 13.4 }, { 23.8, 25.1, 20.6, 17.8 }, { 20.6, 21.5, 18.4, 15.7 } }; // 每日溫度總和及每段溫度總和 double Mon, Tue, Wed, Thu, Time1, Time2, Time3; Mon = Tue = Wed = Thu = Time1 = Time2 = Time3 = 0; // 列印標題欄位 System.out.println("\t" + "星期一\t星期二\t星期三\t星期四"); // for迴圈印出各欄位資料 for (int i = 0; i < a.length; i++) { // 印出左欄標題 System.out.print("時段 " + (i + 1) + "\t"); // 列印各欄位溫度 for (int j = 0; j < a[i].length; j++) { System.out.print(a[i][j] + "\t"); } // 斷行從新的一行開始印 System.out.println(); } // 星期一的溫度總和,就是a[0][0]+a[1][0]+a[2][0] // 星期二的溫度總和,就是a[0][1]+a[1][1]+a[2][1] // 星期三的溫度總和,就是a[0][2]+a[1][2]+a[2][2] // 星期四的溫度總和,就是a[0][3]+a[1][3]+a[2][3] // 利用for迴圈,每日有三個時段,迴圈次數3次,小於a.length for (int i = 0; i < a.length; i++) { Mon = Mon + a[i][0]; Tue = Tue + a[i][1]; Wed = Wed + a[i][2]; Thu = Thu + a[i][3]; } // 除以天數 System.out.println(); System.out.printf("星期一的平均溫度為 %.1f\n", Mon / 3); System.out.printf("星期二的平均溫度為 %.1f\n", Tue / 3); System.out.printf("星期三的平均溫度為 %.1f\n", Wed / 3); System.out.printf("星期四的平均溫度為 %.1f\n", Thu / 3); // 時段1的溫度總和,就是a[0][0]+a[0][1]+a[0][2]+a[0][3] // 時段2的溫度總和,就是a[1][0]+a[1][1]+a[1][2]+a[1][3] // 時段3的溫度總和,就是a[2][0]+a[2][1]+a[2][2]+a[2][3] // 利用for迴圈,每個時段有四天的紀錄,迴圈次數4次,小於a[1].length for (int i = 0; i < a[1].length; i++) { Time1 = Time1 + a[0][i]; Time2 = Time2 + a[1][i]; Time3 = Time3 + a[2][i]; } // 除以時段數 System.out.println(); // 使用printf()印出,%.1f代表浮點數格式化碼,.1代表進位至小數點後1位 // Time1除以4後,將值填入%.1f的位置 System.out.printf("時段一的平均溫度為 %.1f\n", Time1 / 4); System.out.printf("時段一的平均溫度為 %.1f\n", Time2 / 4); System.out.printf("時段一的平均溫度為 %.1f\n", Time3 / 4); }}
- 輸出結果:
星期一 星期二 星期三 星期四時段 1 18.2 17.3 15.0 13.4 時段 2 23.8 25.1 20.6 17.8 時段 3 20.6 21.5 18.4 15.7
星期一的平均溫度為 20.9星期二的平均溫度為 21.3星期三的平均溫度為 18.0星期四的平均溫度為 15.6
時段一的平均溫度為 16.0時段一的平均溫度為 21.8時段一的平均溫度為 19.1
文章標籤
全站熱搜
留言列表