对角线填充阵列

Fill an array diagonally

本文关键字:阵列 填充 对角线      更新时间:2023-10-16

我有以下程序。使用输入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运行,并且仅在测试系统中才有此类问题。

嗨,尝试使用选项卡。

#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;

}

不记得我如何在中学解决这个问题,但是 n小于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 
*/