填充阵列对角线
问题描述:
我有以下程序。与输入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;
}
答
不记得我是如何解决在中学这个问题,但小于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
*/
欢迎堆栈溢出。请花些时间阅读[The Tour](http://stackoverflow.com/tour),并参阅[帮助中心](http://stackoverflow.com/help/asking)中的资料,了解您可以在这里问。 –
我投票关闭这一问题作为题外话,因为它不是编程,而是使用测试系统 – RiaD
的网站,我敢肯定,它没有只在浏览器的打印结果,当你(例如,第一空间标签被跳过)。只需修复一切,它就会工作。请注意,您打印了不同的号码 – RiaD