简体   繁体   English

如何在使用2D数组时将有序对转换为3x3矩阵C ++

[英]How do I turn an ordering pair into a 3x3 matrix in using 2D arrays c++

I'm trying to turn an ordered pair of numbers into a 3x3 matrix and am having troubles writing the conversion. 我正在尝试将有序数字对转换为3x3矩阵,并且在编写转换时遇到麻烦。

I've tried multiple variations of nested for loops to solve this issue, but I'm not getting the desired results. 我尝试了嵌套for循环的多种变体来解决此问题,但没有得到理想的结果。

This is my current attempt: 这是我目前的尝试:

  for(i = 0; i < 6; i++) {
    row = matrixAin[i][0];
    col = matrixAin[i][1];

    for(j = 1; j <= row; j++) {
      for(int k = 1; k <= col; k++) {
        matrixA[j][k] = 1;
      }
    }
  }

This is all the code I have: 这是我所有的代码:

  #include <iostream>
  using namespace std;

  int main() {

    int matrixAin[6][2]; // ordered pair of Matrix A
    int matrixA[3][3];   // 3x3 matrix of Matrix A
    int i, j, row, col;  // for the for loops

    // Sets Matrix A & B values to 0
    for (i = 0; i < 3; i++) {
        for(j = 0; j < 3; j++) {
            matrixA[i][j] = 0;
            matrixB[i][j] = 0;
        }
    }

    // input of Matrix A
    cout << "Please input the ordered pairs for matrix A: ";
    for (i = 0; i < 6; i++) {
        cin >> matrixAin[i][0] >> matrixAin[i][1]; // row , col
    }

    // sets row / col to 1 for Matrix 3x3
    // this is the code with the issue
    for(i = 0; i < 6; i++) {
        row = matrixAin[i][0];
        col = matrixAin[i][1];

        for(j = 1; j <= row; j++) {
            for(int k = 1; k <= col; k++) {
                matrixA[j-1][k] = 1;
            }
        }
    }

    // Displays matrix A
    cout << "A= ";
    for(int i = 0; i < 3; i++) {
        for (int j = 0; j < 3; j++) {
            cout << matrixA[i][j] << ' ';
        }
        cout << endl;
    }

}

This is what the input for this matrix should look like 这是此矩阵的输入应为

Please input the ordered pairs for matrix A: 请输入矩阵A的有序对:

1 2 1 2

1 3 1 3

2 1 2 1

2 2 2 2

3 2 3 2

3 3 3 3

This is the expected results: 这是预期的结果:

A = A =

0 1 1 0 1 1

1 1 0 1 1 0

0 1 1 0 1 1

Your current code takes in each pair and then for each subrectangle of size row x col , sets the area of the rectangle to 1. It's really close. 您当前的代码接受每一对,然后对于大小为row x col每个子矩形,将矩形的面积设置为1。这确实很接近。 You just need to set once for each ordered pair: 您只需为每个有序对设置一次:

for(i = 0; i < 6; i++) {
    row = matrixAin[i][0];
    col = matrixAin[i][1];
    matrixA[row - 1][col - 1] = 1;
}

Replace the inner for-loop with matrixA[row - 1][col - 1] = 1; matrixA[row - 1][col - 1] = 1;替换内部for循环matrixA[row - 1][col - 1] = 1; . Do not forget to check if col and row are between 1 and 3. 不要忘记检查col和row是否在1到3之间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM