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

I´m studing for an exam, i need help! C++

本文关键字:帮助 C++ 学习 考试      更新时间:2023-10-16

好吧,我必须做这个练习,我现在不知道如何通过这种方式显示这个数组 2D 这是练习:

这是我所做的:

#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;
    }
}

好吧,我的疑问是如何通过这个矩阵,因为我的问题是如何从加法到减去行和列进行更改。我是信息学第一的学生,在成为菜鸟时,我有一些正常的怀疑。任何帮助都会有所帮助,谢谢。

考虑一下索引。比如说,您将对行进行i,对列、rows行和columns列进行j

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

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

接下来,对于i=rows-1j=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--;
        }
    }
}