鍵盤輸入 N 位學生成績,計算平均分、最高分、最低分。
package com.azhi;
import java.util.Scanner;
public class ScoreStats {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("請輸入學生人數:");
int n = sc.nextInt();
double[] scores = new double[n];
for (int i = 0; i < n; i++) {
System.out.print("請輸入第 " + (i+1) + " 位學生成績:");
scores[i] = sc.nextDouble();
}
// 平均
double sum = 0;
for (double v : scores) sum += v;
System.out.println("平均成績:" + (sum / n));
// 最高(擂台法)
double max = scores[0];
for (int i = 1; i < n; i++)
if (scores[i] > max) max = scores[i];
System.out.println("最高成績:" + max);
// 最低
double min = scores[0];
for (int i = 1; i < n; i++)
if (scores[i] < min) min = scores[i];
System.out.println("最低成績:" + min);
sc.close();
}
}
length 屬性獲取長度,避免硬編碼。new double[n]、{1,2,3}、new double[]{1,2,3}。0/0.0/false/null。sc.close() 釋放資源習慣。