簡體   English   中英

二維數組中列的總和,Java

[英]Sum of the column in 2D Array, Java

我試圖對每一列求和,但我沒有得到預期的輸出,正如你所看到的,我像正常(行和列)一樣取這個二維數組的元素,但對於 For 循環,我先循環列然后循環行。

輸入;

3
4
1 2 3 4
4 5 6 5
7 8 9 5

預計出局;

12
15
18
14

我的輸出;

6
13
18
22

我的代碼;

import java.util.Scanner;
    public class exercise2_2darray {
        public static void main(String[] args) {
            
            Scanner sc=new Scanner(System.in);   
            int m = sc.nextInt();  //take input row 
            int n = sc.nextInt();  //take input col 
            int array[][] = new int[m][n];      
            
            for(int col =0; col<n; col++) { 
                  int Sum = 0; 
                  
                for (int row=0;row<m; row++) {
                        
                    array[row][col] = sc.nextInt();     
                    Sum+=array[row][col];               
                }           
                System.out.println(Sum);            
            }   
        }
    }

正確的答案是將接受用戶輸入的 for 循環和數組 sum 循環分開;

import java.util.Scanner;
public class exercise2_2darray {
    public static void main(String[] args) {
        
        Scanner sc=new Scanner(System.in);   
        int m = sc.nextInt();  //take input row 
        int n = sc.nextInt();  //take input col 
        int array[][] = new int[m][n];      
        
        for(int row =0; row<m; row++) { 
                  
            for (int col=0;col<n; col++) {
                    
                array[row][col] = sc.nextInt();                         
            }                               
        }
        
        for(int col =0; col<n; col++) { 
              int Sum = 0; 
              
            for (int row=0;row<m; row++) {
                        
                Sum+=array[row][col];               
            }           
            System.out.println(Sum);            
        }   
        
    }
}

您輸入的方式是錯誤的。 您可以切換行和列,這導致您的輸入是這樣的。

1  4  6  8
2  4  5  9
3  5  7  5

和總和

6  13  18  22

要么你必須改變你輸入的方式

1  4  7
2  5  8
3  6  9
4  5  5

或將行和列切換回通常(行作為外循環,列作為內循環)以在另一個循環中分別獲取輸入和sum

for(int row=0; row<r; row++) {
    for(int col=0; col<n; col++) {
        ....// take input
    }
}
for(int row=0; row<r; row++) {
    int sum=0;
    for(int col=0; col<n; col++) {
        Sum+=array[row][col];
    }
    System.out.println(Sum);
}

暫無
暫無

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

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