這是我正在解決的問題:編寫一個程序,讀取一個 3 x 4 矩陣并分別顯示每列和每行的總和。這是示例運(yùn)行:逐行輸入 3×4 矩陣:1.5 2 3 45.5 6 7 89.5 1 3 1Sum of the elements at column 0 is 16.5Sum of the elements at column 1 is 9.0Sum of the elements at column 2 is 13.0Sum of the elements at column 3 is 13.0Sum of the elements at Row 0 is: 10.5Sum of the elements at Row 0 is: 26.5Sum of the elements at Row 0 is: 14.5這是我想出的代碼:package multidimensionalarrays;public class MultidimensionalArrays { public static void main(String[] args) { double sumOfRow = 0; double[][] matrix = new double[3][4]; java.util.Scanner input = new java.util.Scanner(System.in); //Scanner System.out.println("Enter a 3 by 4 matrix row by row: "); //Prompt user to enter matrix numbers for (int row = 0; row < matrix.length; row++) { for (int col = 0; col < matrix[0].length; col++) { matrix[row][col] = input.nextDouble(); } } double[] sumOfCol =new double[matrix[0].length]; for (int i = 0; i < matrix.length; i++) { //row for (int j = 0; j < matrix[i].length; j++) { //column sumOfRow += matrix[i][j]; sumOfCol[j] += matrix[i][j]; } System.out.println("Sum of the elements at row " + row + " is: " + sumOfRow); } System.out.println("Sum of the elements at column " + col + " is: " + sumOfCol); } } 我的問題是,當(dāng)最后打印列和行的總和時,它無法識別row或col變量。我一直在玩它,現(xiàn)在可能已經(jīng)改變了幾個小時,但我似乎無法做到這一點,有人可以幫助我解決我做錯了什么嗎?另外我不知道我是否正確地進(jìn)行了列求和?
添加回答
舉報
0/150
提交
取消