【问题标题】:How to print one side of the diagonal of an array?如何打印数组对角线的一侧?
【发布时间】: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 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;
}

运行代码后,我得到的形状是正确的,但元素与主​​数组不对应。我不知道是什么问题。

【问题讨论】:

  • 听起来你可能需要学习如何使用调试器来单步调试你的代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。延伸阅读: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


【解决方案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";
}

【讨论】:

  • @Dr.lackedu 是的,请详细说明并告诉我们是什么让您认为这不起作用
  • @Dr.lackedu 你可以删除你所有的cmets到这个答案,因为它们现在已经过时了。
  • @Jabberwocky,请告诉我如何打印对角线的下边
  • @Dr.lackedu 这是一个不同的问题!不要以完全改变你原来的问题的方式改变你的问题!
  • 抱歉 Korel,该消息是给 @Dr.lackedu 的,已编辑。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-08-26
  • 1970-01-01
相关资源
最近更新 更多