Как выполнять операции Matrix Math с использованием массивов в C ++ - PullRequest
0 голосов
/ 08 октября 2019

У меня проблема с домашней работой, которая требует использования матриц 4х4, хранящихся в массивах (со значениями, вводимыми пользователем), и я должен выполнить несколько различных математических операций над ними, а также иметь возможность отображать и транспонировать их,Мне нелегко с логикой для добавления и умножения матриц, в частности, как я выбираю конкретные индексы в матрицах для выполнения операций. Мне также трудно понять, как отображать матрицы, поэтому моя функция displayMatrix пуста. Я также изо всех сил пытаюсь выяснить, как сохранить мой пользовательский ввод в различных матрицах в моем цикле for.

Я не совсем уверен, как именно сделать код, который у меня работает, и был бы признателенЛюбые решения или другие советы, которые кто-либо имеет для моего кода!

#include<iostream>
#include<string>

using std::cout;
using std::cin;
using std::endl;
using std::string;

const int SIZE = 4;
const int SLICES = 25;

void addMatrices(int matrix1[][SIZE], int matrix2[][SIZE], int result[][SIZE], 
    int matricesUsed, string prompt);
void displayMatrix(int matrix1[][SIZE], int result[][SIZE]);

int main()
{
    int matrix1[SIZE];
    int matricesUsed = 0;

    string prompt = "Enter the number of matrices you want to use (between 1 & 25): ";
    int initialMatrices;
    cout << prompt;
    cin >> initialMatrices;

    if (initialMatrices <= 0 || initialMatrices > 25)
    {
        cout << "Invalid number of matrices. Please enter a number between 1 and 25." << endl;
        cout << "Enter the number of matrices you want to use (between 1 & 25): ";
        cin >> initialMatrices;
    }

    matricesUsed = initialMatrices - 1;

    for (int i = 0; i < initialMatrices; i++)
    {
        for (int i = 0; i < SIZE; i++)
        {
            cout << "Enter the value for position " << i + 1 << ": ";
            cin >> matrix1[i];
        }
    }
    matricesUsed++;
void addMatrices(int matrix1[][SIZE], int matrix2[][SIZE], int result[][SIZE], int matricesUsed, string prompt)
{
    int firstIndex = getIndex(matricesUsed, prompt);
    int firstIndex = getIndex(matricesUsed, prompt);
    addMatrices(matrix1[], matrix[], result[matricesUsed]);
    displayMatrix(matrix[matricesUsed]);
    matricesUsed++; 
}
void displayMatrix()
{

}

Ожидаемый результат - матрица 4x4, которая получила оператор, указанный пользователем (я пропустил эту часть кода, потому что он работает нормально, нопожалуйста, дайте мне знать, если мне нужно также загрузить его!).

Вывод программы должен выглядеть следующим образом:

How many initial matrices? 2
Enter matrix 1:
 Row 1? 2 4 0 1
 Row 2? 3 0 1 2
 Row 3? 1 0 1 -1
 Row 4? 0 1 2 0
Enter matrix 2:
 Row 1? 1 0 0 0
 Row 2? 0 1 0 0
 Row 3? 0 0 1 0
 Row 4? 0 0 0 1
Operation? +
First matrix for +? 1
Second matrix for +? 2
Result is matrix 3:
 Row 1: 3 4 0 1
 Row 2: 3 1 1 2
 Row 3: 1 0 2 -1
 Row 4: 0 1 2 1

1 Ответ

0 голосов
/ 08 октября 2019

Я думаю, вы можете попробовать использовать двойной цикл для обхода выходной матрицы.

Вот мой код:

#include <iostream>

using namespace std;

int main()
{
    int matrix_1[4][4];
    cout << "Please enter the value of the matrix:" << endl;
    for (auto i = 0; i < 4; i++)
    {
        for (auto j = 0; j < 4; j++)
        {
            cin >> matrix_1[i][j];
        }
    }
    printf("The matrix_1 is:\n");
    for (auto i = 0; i < 4; i++)
    {
        for (auto j = 0; j < 4; j++)
        {
            printf("%8d", matrix_1[i][j]);
        }
        printf("\n");
    }


    int matrix_2[4][4];
    cout << "Please enter the value of the matrix:" << endl;
    for (auto i = 0; i < 4; i++)
    {
        for (auto j = 0; j < 4; j++)
        {
            cin >> matrix_2[i][j];
        }
    }
    printf("The matrix_2 is:\n");
    for (auto i = 0; i < 4; i++)
    {
        for (auto j = 0; j < 4; j++)
        {
            printf("%8d", matrix_2[i][j]);
        }
        printf("\n");
    }

    int matrix_3[4][4];
    for (auto i = 0; i < 4; i++)
    {
        for (auto j = 0; j < 4; j++)
        {
            matrix_3[i][j] = 0;
        }
    }

    cout << "operation:*" << endl;

    for (auto i = 0; i < 4; i++) //The number of rows in matrix 1 is 4.
    {
        for (auto j = 0; j < 4; j++)//The number of columns in matrix 2 is 4.
        {   
            for (auto k = 0; k < 4; k++) //The number of columns in matrix 1 is 4.
            {
                matrix_3[i][j] += matrix_1[i][k] * matrix_2[k][j];
            }

        }
    }
    cout << "The value of the output matrix:" << endl;
    for (auto i = 0; i < 4; i++)
    {
        for (auto j = 0; j < 4; j++)
        {
            printf("%8d", matrix_3[i][j]);
        }
        printf("\n");
    }


    int matrix_4[4][4];
    for (auto i = 0; i < 4; i++)
    {
        for (auto j = 0; j < 4; j++)
        {
            matrix_4[i][j] = 0;
        }
    }

    cout << "operation:+" << endl;

    for (auto i = 0; i < 4; i++)
    {
        for (auto j = 0; j < 4; j++)
        {
            matrix_4[i][j] += matrix_1[i][j] + matrix_2[i][j];
        }
    }

    cout << "The value of the output matrix:" << endl;

    for (auto i = 0; i < 4; i++)
    {
        for (auto j = 0; j < 4; j++)
        {
            printf("%8d", matrix_4[i][j]);
        }
        printf("\n");
    }

    return 0;
}
...