1. 程式人生 > >典型陣列處理程式碼

典型陣列處理程式碼

package com.arithmetic;

import java.util.Arrays;

public class Array {

    // 獲得陣列最大值
    public static double getMaxValue(double[] array) {
        double maxValue = array[0];
        for (int i = 0; i < array.length; i++) {
            if (array[i] > maxValue) {
                maxValue =  array[i];
            }
        }
        return maxValue;
    }

    // 計算陣列內元素平均值
    public static double getAverage(double[] array) {
        int len =  array.length;
        double sum = 0;
        for (int i = 0; i < len; i++) {
            sum += array[i];
        }
        return sum / len;
    }

    // 複製陣列
    public static double[] copyArray(double[] array) {
        double[] copyArray = new double[array.length];
        for (int i = 0; i < array.length; i++) {
            copyArray[i] = array[i];
        }
        return copyArray;
    }

    // 顛倒陣列順序
    public static double[] reverse(double[] array) {
        int len = array.length;
        for (int i = 0; i < len/2; i++) {
             double temp = array[i];
             array[i] = array[len-1-i];
             array[len-1-i] = temp;
        }
        return array;
    }
    // 矩陣相乘
    public static double 

    public static void main(String[] args) {
        double[] array = {20,10,14,2,19,30};
        System.out.println(getMaxValue(array));
        System.out.println(getAverage(array));
        System.out.println(Arrays.toString(copyArray(array)));
        System.out.println(Arrays.toString(reverse(array)));
    }
}