对角线填充阵列
Fill an array diagonally
我有以下程序。使用输入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
*/
相关文章:
- 在c++中用vector填充一个简单的动态数组
- OpenMP阵列性能较差
- 如何使用用户输入在C++中正确填充2D数组
- 如何找到大小'x'数组是否完全填充,在C++?
- 如何将三维尺寸不固定的三维阵列展平为一维阵列
- 当我的阵列太大时出现分段错误
- Cuda C++:设备上的Malloc类,并用来自主机的数据填充它
- 插入并填充全局阵列 LLVM
- 填充 2D 阵列
- 2D阵列试图填充时失败
- 对角线填充阵列
- C 填充动态阵列int
- C++OpenGL坐标阵列来绘制线条/边界和填充矩形
- 将int阵列填充有位
- 我如何用单词填充二维字符阵列
- 如何在没有STL的情况下从2d阵列中删除任何未填充的插槽
- C++填充2D阵列
- 初始化后重新填充阵列
- 创建一个3x3x3阵列.用0到9之间的随机值填充.输出数组.找出3个最小值和3个最大值的输出
- 使用文件路径填充WCHAR阵列