簡體   English   中英

你如何找到二維數組中的最大行

[英]how do you find the max row in a 2d array

創建二維數組說m:

  1. 要求用戶通過鍵盤輸入行和列的大小(使用掃描儀)。 N IS 9,如果用戶輸入的列大小大於N + 4,則要求用戶重新輸入列大小
  2. 使用隨機對象將所有數組元素填充為(3.0,13.0)范圍內的雙數
  3. 傳遞上面的數組m並調用以下兩個方法

    • findMaxRow(double[][]array) ,找到並打印2D數組中最大的列總和
    • returnAvg(m) ,打印出數組m的平均值

評論:

因此,我編寫了代碼以找到最大Colm,但是我不知道如何找到最大Row。 我需要能夠找到“最大行”,但是由於我的代碼找到了cllm而不是最大行,因此我正在尋找方法。

這是我的代碼:import java.util.Scanner;

  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    Random rand = new Random();

    System.out.print("Number of Rows? ");
    int rows = input.nextInt();
    System.out.print("Number of Columns? ");
    int columns = input.nextInt();
    while (columns > 7) { // check for column > n+5 where n = 2 in my case
        System.out.print("The column amount is too high. Try another number: ");
        columns = input.nextInt();
    }

    double[][] m = new double[rows][columns];

    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < columns; j++) {
            m[i][j] = rand.nextDouble()*7+4;
        }
    }
    findMaxCol(m);
    System.out.println("The average value of this array is "+returnAvg(m));
}
public static void findMaxCol(double[][] a) {
    double[] maxCol = new double[a[0].length];
    double max = 0;
    int maxColNum=0;
    for (int i = 0; i < a[0].length; i++) { // Sum of Columns
        for (int j = 0; j < a.length; j++) {
            maxCol[i]+=a[j][i];
        }
    }
    //System.out.println(Arrays.toString(maxCol));
    for (int i = 0; i < maxCol.length; i++) {
        if (max < maxCol[i]) {
            max = maxCol[i];
            maxColNum = i; // column number will associate with its array column starting with 0
        }
    }
    System.out.println("The highest column sum is Column #"+maxColNum+" with a sum of "+max);
}
public static double returnAvg(double[][] a) {
    double sum = 0; // initialization
    for (int i = 0; i < a.length; i++) {
        for (int j = 0; j < a[i].length; j++) {
            sum+=a[i][j];
        }
    }
    // System.out.println(sum); Test line
    return (sum/(a.length*a[0].length)); // avg
}

}

不確定我是否了解您想要的結果,但是這應該為您提供最大金額的行以及該金額是多少。 請注意,這並未考慮總和相等的多行。 它將報告總和最大的數組中的第一行。

public static void findMaxRow(double[][] a){

    double maxSum = 0;
    int maxRow = 0;

    for (int row = 0; row < a.length; row++){

        double rowSum = 0;

        for (int column = 0; column < a[row].length; column++){
            rowSum += a[row][column];
        }

        if (rowSum > maxSum){
            maxSum = rowSum;
            maxRow = row;
        }
    }

    // maxSum should be the greatest sum of any row
    // maxRow is the row that contained the greatest sum
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM