假设我们有一个5 X 5的随机数组
1 2 3 7 8
4 7 3 6
5
2 9 8
4 2
2 9
5 4 7
3
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;
}
运行代码后,得到的形状是正确的,但元素与主数组不对应。我不知道是什么问题。
答案 0 :(得分:1)
左侧:
for (size_t i = 0; i < rows; i++) {
for(size_t j = 0; j < columns - i; j++) {
cout << array[i][j] << " ";
}
cout << "\n";
}
右侧:
for (size_t i = 0; i < rows; i++) {
for (size_t j = 0; j < columns; j++) {
if (j < columns - i - 1) cout << "- ";
else cout << vec[i][j] << " ";
}
cout << "\n";
}