2016-02-08 50 views
0

編輯:我相當新的C++。兩週前開始使用這種語言。我如何輸出二維數組的行總和C++

對不起,如果之前已經詢問過這個問題,但是我已經在網上搜索瞭如何在二維數組中搜索單個行並且找不到我正在尋找的答案。

我需要顯示[m] [n]中每個單獨行的總和,但由於某種原因,這隻適用於我的數組爲2x2,但如果它是3x3或更大,那麼我得到以下輸出終端:

for intsance, a[3][3]= 
{1,2,3}, //this is determined by the user 
{1,2,3}, 
{1,2,3}; 

then i get the following output: 
9179942 //address of some sort??? 
6  // actual sum. code is working here (yay :D) 
469090925// again something i dont understand 

這是我迄今爲止

#include <iostream> 
using namespace std; 
int main(){ 
int m,n; 
cout<<"Enter number of rows for array"<<endl; 
cin>>m; 
if (m>10){ 
    cout<<"More than 10 rows will be too big"<<endl; 
    return 1; 
} 
cout<<"Enter number of collumns for array"<<endl; 
cin>>n; 
if (n>10){ 
    cout<<"More than 10 collumns will be too big"<<endl; 
    return 1; 
} 
int a[m][n]; 
for(int i=0; i<m;i++){ 
    cout<<"Enter "<<m<<" values into row "<<i+1<<endl; 
    for(int j=0; j<n; j++){ 
     cout<<"a ["<<i<<"]["<<j<<"]: "; 
     cin>>a[i][j]; 
    } 
} 
cout<<"Array dimensions: "<<m<<"x"<<n<<'\n'<<"resulting array: "<<endl; 
for(int i=0; i<m;i++){ 
    for(int j=0; j<n; j++){ 
     cout<<a[i][j]<<" "; 
    } 
    cout<<endl; 
} 
int avg[m]; 
int el_less_avg; 
for(int i=0; i<m; i++){ 
    for(int j=0; j<n;j++){ 
     avg[i]+=a[i][j]; 
    } 
}cout<<"\n\n"; 
for(int i=0; i<m; i++){ 

    cout<<avg[i]<<endl; 
} 

return 0; 
} 
+0

初始化您的數據。 – alcedine

+0

[如何在C++中打印二維數組?]可能的重複(http://stackoverflow.com/questions/12311149/how-to-print-2d-arrays-in-c) – johnbakers

+0

我的問題是爲什麼我得到奇怪的輸出...有什麼我想念? –

回答

1
int avg[m]; 
int el_less_avg; 
for(int i=0; i<m; i++){ 
    for(int j=0; j<n;j++){ 

你不初始化這些值,以便他們可以自由地將任何多餘的內容是在棧上的時間。你需要初始化它們。

int avg[m]; 
for (int i = 0; i < m; ++i) { 
    avg[i] = 0; 
    for (int j = 0; j < n; ++j) { 
     avg[i] += a[i][j]; 
    } 
} 
1

int a[m][n];在標準C++中是不允許的。編譯時必須知道C風格數組的維數。使用這段代碼的程序可以做任何事情。

你可以將其替換這一行:

vector<vector<int>> a(m, vector<int>(n)); 

這似乎是在第一拗口,但你會發現它使你的問題消失。

這種方法的另一個好處是,你可以再使用基於範圍的循環:

for(int x : avg) 
    cout << x << endl; 

從而降低了通過使用循環條件錯信犯錯誤的機會。