求出數組中元素的最大值和最小值

方法其實很簡單

一個數組中有很多元素 要知道最大值

只要將其中任意兩個元素拿出來比較

暫時將其中大的那一個假定爲最大值

再將其他元素與這個最大值比較

如果有更大的 它將替換原來假定的最大值

再與其它元素比較

以此類推直到所有的元素的值都比較完

就能得到最大值

最小值的方法也是一樣


如:通過輸入獲得全班成績 求出全班的總成績 平均分 最高分和最低分

這裏我們利用兩個for循環來實現

public class TestScore {
    public static void main(String[] args) {
        int[] scores = new int[5];
        float total = 0;
        float avg = 0;
        int max = 0;
        int min = 0;
        Scanner input = new Scanner(System.in);
        System.out.println("請輸入5個學生的筆試成績");
        for (int i = 0; i < scores.length; i++) {
            scores[i] = input.nextInt();
        }
        max = scores[0];
        min = scores[0];
        for (int j = 0; j < scores.length; j++) {
            //總成績
            total += scores[j];
            //平均成績
            avg = total / scores.length;

          //求出最高分和最低分
            if (scores[j] > max) {
                max = scores[j];
            }
            if (scores[j] < min) {
                min = scores[j];
            }
        }
        System.out.println("總成績:" + total);
        System.out.println("平均分:" + avg);
        System.out.println("最高分:" + max);
        System.out.println("最低分:" + min);
    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章