Я не могу найти ошибку в моей программе калькулятора матрицы C ++ - PullRequest
0 голосов
/ 11 февраля 2020

Я работаю над матричным калькулятором. В настоящее время я сосредоточен на функциях сложения и вычитания.

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

При компиляции я не получаю синтаксис ошибки, так что это, вероятно, логическая ошибка. Я попытался просмотреть свой код, чтобы найти ошибку, но все еще не могу ее найти.

Пожалуйста, помогите мне найти причину, по которой происходит задержка, а затем происходит сбой после ввода 2 матриц при сложении или вычитании.

#include <iostream>
#include <vector>
#include <conio.h> // for _getch
std::vector < std::vector<double> > matrix_1;
std::vector < std::vector<double> > matrix_2;
int rows_1;
int columns_1;
int rows_2; //This is for the second matrix when multiplying
int columns_2; //This is for the second matrix when multiplying
std::vector < std::vector<double> > result; //This is for storing the result
int operation;//This variable is for the user to choose the operation
double input;//This is for the user input for the values inside the Matrices
//---------------------------------------------------------------------------------------------------------------------
//The below function is for being to able to give input without inserting a new line
double get_input()
    {std::string word ="";
    char c = _getch();
    while (not(std::isspace(c)))
        {word.push_back(c);
        std::cout<<c;
        c=_getch();
        }
    std::cout<< c;
    input = std::stod(word);
    return input;}
//The below function is for creating a matrix
std::vector < std::vector<double> > create_matrix(std::vector < std::vector<double> > matrix, int rows, int columns){
    for (int i =0; i<rows; i++)
            {std::vector<double> row ={};
            for (int j = 0; j<columns; j++){
                if (rows==1 and columns==1){
                    std::cout<<"[ ";
                    input = get_input();
                    row.push_back(input);
                    std::cout<<"]"<<"\n";}
                else if ((j==0 and i==0) or (j==0 and i==(rows-1)))
                {std::cout<<"[ ";
                input = get_input();
                row.push_back(input);
                std::cout<<" ";}
                else if ((j==(columns-1) and i==0) or (j==(columns-1) and i==(rows-1)))
                {input = get_input();
                std::cout<<" ]"<<"\n";
                row.push_back(input);}
                else if (j==0){ std::cout<<"| ";
                                input= get_input();
                                row.push_back(input);
                                std::cout<<" ";}
                else if (j==(columns-1)){input = get_input();
                                    std::cout<<" |";
                                    row.push_back(input);
                                    std::cout<<"\n";}
                else {input = get_input();
                    row.push_back(input);
                    std::cout<<" ";}
                    }
            matrix.push_back(row);
            }
    return matrix;}
//This function is for addition
void add(){
    std::cout<<"Insert the amount of rows (horizontal - ) there are: ";
    std::cin >> rows_1;
    std::cout<<"Insert the amount of columns (vertical | ) there are: ";
    std::cin >> columns_1;
    std::cout<<"\nENTER EACH NUMBER IN THE FIRST MATRIX SEPARATED BY A SPACE\n\n";
    create_matrix(matrix_1, rows_1, columns_1);
    std::cout<<"\nNow for the creation of the second matrix\n";
    create_matrix(matrix_2, rows_1, columns_1);
    //Creating the result matrix
    result={};
    for (int i=0; i<rows_1; i++)
    {std::vector<double> row = {};
    for (int j=0; j<columns_1; j++)
    {row.push_back((matrix_1[i][j]+matrix_2[i][j]));}
    result.push_back(row);}
    //Printing the result matrix
    std::cout<<"\nHere is the result: \n";
    for (int i=0; i<rows_1; i++)
    {for (int j=0; j<columns_1; j++)
    {if (rows_1==1 and columns_1==1){std::cout<<"[ "<<result[0][0]<<" ]\n";}
    else if ((i==0 and j==0) or (i==(rows_1-1) and j==0)){std::cout<<"[ "<<result[i][j]<<" ";}
    else if ((i==0 and j==(columns_1-1)) or (i==(rows_1-1) and j==(columns_1-1))) {std::cout<<result[i][j]<<" ]\n";}
    else if (j==0){std::cout<<"| "<<result[i][j]<<" ";}
    else if (j==(columns_1-1)) {std::cout<< result[i][j] <<" |";}
    else {std::cout<<result[i][j]<<" ";}}
    }
    }

//This is another function that will do the subtraction. It is the same as the addition one, only that corresponding values are subtracted
void subtract(){
    std::cout<<"Insert the amount of rows (horizontal - ) there are: ";
    std::cin >> rows_1;
    std::cout<<"Insert the amount of columns (vertical | ) there are: ";
    std::cin >> columns_1;
    std::cout<<"\nENTER EACH NUMBER IN THE FIRST MATRIX SEPARATED BY A SPACE\n\n";
    create_matrix(matrix_1, rows_1, columns_1);
    std::cout<<"\nNow for the creation of the second matrix\n";
    create_matrix(matrix_2, rows_1, columns_1);
    //Creating the result matrix
    result={};
    for (int i=0; i<rows_1; i++)
    {std::vector<double> row = {};
    for (int j=0; j<columns_1; j++)
    {row.push_back((matrix_1[i][j]-matrix_2[i][j]));}
    result.push_back(row);}
    //Printing the result matrix
    std::cout<<"\nHere is the result: \n";
    for (int i=0; i<rows_1; i++)
    {for (int j=0; j<columns_1; j++)
    {if (rows_1==1 and columns_1==1){std::cout<<"[ "<<result[0][0]<<" ]\n";}
    else if ((i==0 and j==0) or (i==(rows_1-1) and j==0)){std::cout<<"[ "<<result[i][j]<<" ";}
    else if ((i==0 and j==(columns_1-1)) or (i==(rows_1-1) and j==(columns_1-1))) {std::cout<<result[i][j]<<" ]\n";}
    else if (j==0){std::cout<<"| "<<result[i][j]<<" ";}
    else if (j==(columns_1-1)) {std::cout<< result[i][j] <<" |";}
    else {std::cout<<result[i][j]<<" ";}}
    }
    }
//Create another function that will do the multiplication
void multiply(){/*I will fill the function definition later*/}

//This function is for choosing the operation
void decide(){
    std::cout<<"Select an operation: \n";
    std::cout<<"1. Addition\n";
    std::cout<<"2. Subtraction\n";
    std::cout<<"3. Multiplication\n";
    std::cin >> operation;
    while ((operation!=1) and (operation!=2) and (operation!=3)){
        std::cout<<"Please enter the number of an existing operation: ";
        std::cin >> operation;}
    if (operation==1){ add(); }
    else if (operation==2){ subtract(); }
    else { multiply(); }}
//---------------------------------------------------------------------------------------------------------------------
int main() {
    std::cout<<"-------------------------------------------------------------------\n";
    std::cout<<"MATRIX CALCULATOR\n";
    std::cout<<"-------------------------------------------------------------------\n";
    while(true){decide();}
}

1 Ответ

0 голосов
/ 11 февраля 2020

Ваша create_matrix функция неверна. Он возвращает a std::vector < std::vector<double> >, но ваш код игнорирует возвращаемое значение.

Когда ваш вызов create_matrix(matrix_1, rows_1, columns_1);, matrix_1 не изменится вообще.

Измените функцию create_matrix следующим образом:

void create_matrix(std::vector < std::vector<double> > & matrix, int rows, int columns) {
                                                    // ^ add this
  matrix.clear();   // add this line

  ... the rest of the code is identical to your's

   // and remove the "return matrix;" at the end
}

А также в вашем коде отсутствует следующее:

#include <cctype>
#include <string>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...