我正在学习考试,我需要帮助! C ++

时间:2017-01-22 21:24:21

标签: c++ arrays

好吧,我必须做这个练习,现在我不知道如何以这种方式显示这个数组2D This is the exercise:

这就是我所做的:

#include <iostream>
#include <cmath>
using namespace std;


const int MaxFila    = 8;
const int MaxColumna = 5;

void rellenarVector (int matriz[MaxFila][MaxColumna]);
void MostrarMatriz  (int matriz[MaxFila][MaxColumna]);

int main() {

    int matriz[MaxFila][MaxColumna];
    rellenarVector(matriz);
    MostrarMatriz(matriz);

    return 0;
}

void rellenarVector (int matriz[MaxFila][MaxColumna]){

    cout << "introduce los valores de la matriz: " << endl;
    for(int i = 0; i < MaxFila; i++){
        for(int j = 0; j < MaxColumna; j++){
            cin >> matriz[i][j];
        }
    }
}

void MostrarMatriz (int matriz[MaxFila][MaxColumna]){

    int Filaux = 0, columaux = 0;

    for(int i = Filaux; i < MaxFila; i++){

        for(int j = columaux; j < MaxColumna; j++){
            cout << matriz[i][j] << " ";
        }
        cout << endl;
    }

}

我的疑问是如何通过这个矩阵,因为我的问题是如何从添加到减去行和列进行更改。我是第一个提供信息的学生,而且当我是菜鸟时,我有一些正常的疑虑。任何帮助都会有所帮助,谢谢。

1 个答案:

答案 0 :(得分:0)

想想索引。比方说,行ijrows行和columns列为i=0

首先,对于行j=0,您必须打印从columns-1j=columns-1的所有列。

接下来,对于i=1列,您必须打印所有行减去第一行,从rows-1i=rows-1

接下来,对于j=columns-1,请将j=0打印到//make sure to obtain columns and rows from to your matrix int columns=5; int rows=8; int direction=1; //let say 1 is left to right (start direction), 2 is up to down, 3 is right to left and 4 is down to up int i=0, j=0; //set the limits where it must change direction int minJ=0, maxJ=columns-1, minI=1, maxI=rows-1, totalElements=rows*columns; for(int k=0;k<totalElements;k++) { //stop when all elements have been printed cout<<matriz[i][j]<<" "; //move one index based on the direction if(direction==1) { //check if direction must change, otherwise advance in this direction if(j==maxJ) { //now go down direction=2; //reduce the limits, because the next time its going in this direction, the last element will already have been printed maxJ--; //also move the pointer in the new direction so in the next loop it prints the next element i++; } else { j++; } } else if(direction==2) { if(i==maxI) { //now go left direction=3; maxI--; j--; } else { i++; } } else if(direction==3) { if(j==minJ) { //now go up direction=4; minJ++; i--; } else { j--; } } else if(direction==4) { if(i==minI) { //now go right again direction=1; minI++; j++; } else { i--; } } }

等等。

Streets