【发布时间】:2019-03-31 11:30:45
【问题描述】:
假设我们有一个 5 X 5 的随机数组
1 2 3 7 8
4 7 3 6 5
2 9 8 4 2
2 9 5 4 73 7 1 9 8
现在我想打印上面显示的对角线的右侧,以及对角线中的元素,比如
----------8
--------6 5
------8 4 2
---9 5 4 7
3 7 1 9 8
我写的代码是
#include <iostream>
#include <time.h>
using namespace std;
int main(){
int rows, columns;
cout << "Enter rows: ";
cin >> rows;
cout << "Enter colums: ";
cin >> columns;
int **array = new int *[rows]; // generating a random array
for(int i = 0; i < rows; i++)
array[i] = new int[columns];
srand((unsigned int)time(NULL)); // random values to array
for(int i = 0; i < rows; i++){ // loop for generating a random array
for(int j = 0; j < columns; j++){
array[i][j] = rand() % 10; // range of randoms
cout << array[i][j] << " ";
}
cout << "\n";
}
cout << "For finding Max: " << endl;
for(int i = 0; i < rows; i++){//loop for the elements on the left of
for(int j = columns; j > i; j--){//diagonal including the diagonal
cout << array[i][j] << " ";
}
cout << "\n";
}
cout << "For finding Min: " << endl;
for(int i = rows; i >= 0; i++){ //loop for the lower side of
for(int j = 0; j < i - columns; j++){ //the diagonal
cout << array[i][j] << " ";
}
cout << "\n";
}
return 0;
}
运行代码后,我得到的形状是正确的,但元素与主数组不对应。我不知道是什么问题。
【问题讨论】:
-
听起来你可能需要学习如何使用调试器来单步调试你的代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。延伸阅读:How to debug small programs
-
for (int j = columns->for (int j = columns -1,否则你访问数组越界,但无论如何这不是你真正想要的 -
我想要包括边界
-
@Dr.lackedu
array[rows][columns]越界。数组右下元素为array[rows - 1][columns - 1],左上元素为array[0][0] -
如果您想添加不同的问题,在得到回答后,您可以打开新问题 r 添加(而不是替换)您的新问题。
标签: c++ arrays c++11 visual-c++ multidimensional-array