2016-12-27 156 views
0

我有以下程序。與輸入3 5填充陣列對角線

3 rows 
5 growth of numbers 

輸出應該是:

1 2 4 7 10 
3 5 8 11 13 
6 9 12 14 15 

但我的程序給出:

1 2 3 4 5 
    6 7 8 9 10 
    11 12 13 14 15 

這裏是我到目前爲止已經試過

int main() { 
    int n, m, c = 0; 
    cin >> n >> m; 
    int a[n][m]; 

    for (int i = 0; i < n; i++) 
     for (int j = 0; j < m; j++) 
      a[i][j] = ++c; 

    for (int i = 0; i < n; i++) { 
     for (int j = 0; j < m; j++) 
      cout << setw(4) << a[i][j]; 
     cout << endl; 
    } 
} 

我做錯了什麼或失蹤?

關於空間:找不到原因,這種行爲(第一個空格被忽略),顯示在屏幕截圖。試過用不同的編譯器在不同的IDE中運行,並且只有在測試系統中才有這樣的問題。

+4

歡迎堆棧溢出。請花些時間閱讀[The Tour](http://stackoverflow.com/tour),並參閱[幫助中心](http://stackoverflow.com/help/asking)中的資料,瞭解您可以在這裏問。 –

+0

我投票關閉這一問題作爲題外話,因爲它不是編程,而是使用測試系統 – RiaD

+0

的網站,我敢肯定,它沒有隻在瀏覽器的打印結果,當你(例如,第一空間標籤被跳過)。只需修復一切,它就會工作。請注意,您打印了不同的號碼 – RiaD

回答

0

嗨嘗試使用標籤來代替。

#include <iostream> 
using namespace std; 

int main() { 
    int n, m, c = 0; 

    cin >> n >> m; 

    int *a = new int[n * m]; 

    for (int i = 0; i < n; i++) 
     for (int j = 0; j < m; j++) 
      a[i * n + j] = ++c; 

    for (int i = 0; i < n; i++) { 
     for (int j = 0; j < m; j++) 
      cout << "\t" << a[i * n + j]; 
     cout << endl; 
    } 
    delete[] a; 
    return 0; 

}

0

不記得我是如何解決在中學這個問題,但小於mñ少,下面的代碼工作:

#include <iostream> 

using namespace std; 

void nextij(long n,long m,long& i,long& j) { 
    if (i==n-1) { //bottom row 
     if (j<n-1) { //in the left square 
      j = i+j+1; 
      i = 0; 
     } 
     else { //out of the left square 
      i = j-(n-1)+1; 
      j = m-1; 
     } 
    } 
    else { //other rows 
     if (j==0) { //left most column 
      j = i+1; 
      i = 0; 
     } 
     else { //other columns 
      i++; 
      j--; 
     } 
    } 
} 

int main() { 
    long n = 3; 
    long m = 5; 
    long a[3][5]; 

    long i = 0; 
    long j = 0; 
    long c = 1; 

    while (c<=n*m) { 
     a[i][j] = c;   
     nextij(n,m,i,j); 
     c++;   
    } 

    for (i=0; i<n; i++) { 
     for (j=0; j<m; j++) 
      cout <<a[i][j] <<" "; 
     cout <<endl; 
    } 
} 

/* 
output: 
1 2 4 7 10 
3 5 8 11 13 
6 9 12 14 15 
*/