Мои функции не обновляют глобальные переменные / переменные, используемые в main - PullRequest
0 голосов
/ 29 февраля 2020

Мой проект - это несколько простых матричных операций, он должен работать нормально, но моя функция ввода, похоже, не обновляет глобальные переменные, это может быть неправильный тип данных для того, что я пытаюсь сделать, но я Точно сказать не могу. Вот ссылка на то, что должно происходить http://cpp.sh/22kie. также здесь есть ссылка на все с Makefile https://drive.google.com/open?id=1tmIbdEWXJJ54moQKy8rkZODFkXKDU2Nz

вот мой заголовочный файл:

#ifndef project1
#define project1

static int choice, rows1, cols1, rows2, cols2, k;
static char choice2;
static int *mat1 = new int[10 * 10];
static int *mat2 = new int[10 * 10];
static int *matf = new int[10 * 10];

void output(int *matf, int rows, int cols);

void addition(int *mat1, int *mat2, int *matf, int rows, int cols);

void subtraction(int *mat1, int *mat2, int *matf, int rows, int cols);

void multiplication(int *mat1, int *mat2, int *matf, int rows1, int cols1, int rows2, int cols2);

int input();
#endif

вот: мой основной:

#include <string>
#include "project1.h"
using namespace std;

int main()
{

    input();

    switch (choice)
    { //this switch block will call the correct fucntion with respect to the user's choice

    case 1:
        addition(mat1, mat2, matf, rows1, cols1);

        break;

    case 2:
        subtraction(mat1, mat2, matf, rows1, cols1);

        break;

    case 3:
        multiplication(mat1, mat2, matf, rows1, cols1, rows2, cols2);

        break;

    case 0:
        return 0;
    default:
        cout << "invalid 2input";
    }
    //the end of the main function will repeat if the user would like

    cout << "\n Would you like to do another operation y/n?" << endl;
    cin >> choice2;

    if (choice2 == 'y')
    {
        main();
    }
    else
    {
        return 0;
    }
}

и вот входная функция:

int input()

{

    //input function

    cout << "Menu"
         << "\n 1. Addition"
         << "\n 2. Subtraction"
         << "\n 3. Multiplication"
         << "\n 0. Exit"
         << "\n Enter the number of your choice" << endl;
    cin >> choice;

    if (choice == 0)
    { // this will kill the main function if "Exit" is chosen, or repeat if an invalid number is chosen
        return 0;
    }
    else if (choice > 3)
    {
        cout << "invalid input" << endl;
        input();
    }
    else
    {
    }
    //this part of the code will prompt the user for the rows and columns for each matrix
    cout << "Number of rows for the first Matrix? (max 10)" << endl;
    cin >> rows1;

    cout << "Number of columns for the first Matrix? (max 10)" << endl;
    cin >> cols1;

    cout << "Number of rows for the second Matrix? (max 10)" << endl;
    cin >> rows2;

    cout << "Number of columns for the second Matrix? (max 10)" << endl;
    cin >> cols2;

    //this if/else statement checks that the matrices are the right size to be operated
    if ((choice == 1 || choice == 2) && ((cols1 != cols2) || (rows1 != rows2)))
    {
        cout << " error: for addition and subraction the two matrices must have the same amount of elements";
        choice = 0;
        return 0;
    }
    else if ((choice == 3) && (rows2 != cols1))
    {
        cout << " error: for multiplication the columns of the first must equal the rows of the second";
        choice = 0;
        return 0;
    }
    else
    {
    }

    // this for loop allows the user to input each element for the first matrix
    cout << "input the elements of the first matrix: " << endl;

    for (int i = 0; i < rows1; i++)
    {
        for (int j = 0; j < cols1; j++)
        {
            cout << "Enter element "
                 << "(" << i << "," << j << "): ";
            cin >> k;
            *(mat1 + i * cols1 + j) = k;
        }
    }

    output(mat1, rows1, cols1); //this call to output will allow the user to see what they have imputed

    // this for loop allows the user to input each element for the second matrix
    cout << "input the elements of the second matrix: " << endl;
    for (int i = 0; i < rows2; i++)
    {
        for (int j = 0; j < cols2; j++)
        {
            cout << "Enter element "
                 << "(" << i << "," << j << "): ";
            cin >> k;
            *(mat2 + i * cols2 + j) = k;
        }
    }

    output(mat2, rows2, cols2); //this call to output will allow the user to see what they have imputed
}```

Редактировать: Новый основной после переключения всего на локальные переменные:

основной:

#include <iostream>
#include <string>
#include "project1.h"
using namespace std;

int choice, rows1, cols1, rows2, cols2, k;
char choice2;
int *mat1 = new int[10 * 10];
int *mat2 = new int[10 * 10];
int *matf = new int[10 * 10];

int main()
{


    input( choice, rows1, cols1, rows2, cols2, k, mat1, mat2, matf);
cout<<rows1;
    switch (choice)
    { //this switch block will call the correct fucntion with respect to the user's choice

    case 1:
        addition(mat1, mat2, matf, rows1, cols1);

        break;

    case 2:
        subtraction(mat1, mat2, matf, rows1, cols1);

        break;

    case 3:
        multiplication(mat1, mat2, matf, rows1, cols1, rows2, cols2);

        break;

    case 0:
        return 0;
    default:
        cout << "invalid input";
    }
    //the end of the main fucntion will repeat if the user would like

    cout << "\n Would you like to do another operation y/n?" << endl;
    cin >> choice2;

    if (choice2 == 'y')
    {
        main();
    }
    else
    {
        return 0;
    }
}

заголовок:

#ifndef project1
#define project1


int output(int *matf, int rows1, int cols1);

int addition(int *mat1, int *mat2, int *matf, int rows1, int cols1);

int subtraction(int *mat1, int *mat2, int *matf, int rows1, int cols1);

int multiplication(int *mat1, int *mat2, int *matf, int rows1, int cols1, int rows2, int cols2);

int input(int choice,int rows1,int cols1,int rows2,int cols2,int k, int *mat1, int*mat2, int*matf);
#endif

1 Ответ

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

Ваши переменные все еще являются глобальными переменными (объявленными вне функции). Вы должны объявить их внутри main (хотя это не является причиной проблемы).

Проблема теперь в том, что вы передаете свои значения в input по значению. Это означает, что вызывается input, стек увеличивается, а отправляемые вами значения копируются в пространство стека input. Когда вы изменяете их в input, они изменяются в стеке input. input затем возвращается, и эти обновленные значения удаляются. Вместо этого вам нужно отправить ссылки на эти переменные. Это означает, что адрес переменных будет скопирован в стек input, и input будет использовать эти адреса для go возврата к переменной в функции main и обновления этих значений напрямую.

Измените сигнатуру функции для ввода на

void input(int& choice, int& rows1, int& cols1, int& rows2, int& cols2, int& k, int *mat1, int* mat2, int* matf);

Обратите внимание, что возвращаемое значение input изменяется с int на void. Это потому, что когда вы вызываете его в main, вы не назначаете возвращаемое значение input чему-либо, поэтому я предположил, что вам это не нужно. Любые операторы return в input необходимо будет изменить на return; (вместо чего-то вроде return 0;).

Обратите внимание, что после первого амперсанда (&) 6 параметров отправлено на вход. Таким образом, input будет иметь свои адреса и может менять их напрямую. mat1, mat2 и matf уже передаются как указатели, поэтому их не нужно менять.

В чем разница между передачей по ссылке и передачей по значению

...