Pointer changes the value inside function in C ++

2

I have the task of creating four functions that do multiplication, division, addition and subtraction between two numbers given by the user. The operation to be performed must be chosen using the * / - + characters, given by the user.

I need to use pointers to do the operations, the pointer to the first number works fine, but the second, when it enters the function, always changes the value to 0.

#include <iostream>
#include <cstdio>

int mult(int *a, int *b)
{
    return *a *= *b;

}

float div(int *a, int *b)
{
    return *a /= *b;

}

int sub(int *a, int *b)
{
    return *a -= *b;

}

int soma(int *a, int *b)
{
    return *a += *b;

}


int main()
{
    int num1, num2;
    char op;

    printf("Digite o primeiro numero: ");
    scanf("%d", &num1);
    printf("\nDigite o segundo numero: ");
    scanf("%d", &num2);

    printf("\nNumeros: %d e %d", num1, num2);

    printf("\nDigite a operacao a ser realizada (* / - +): ");
    scanf("%s", &op);

    if (op == '*')
    {
        printf("\n%d * %d = %d\n", num1, num2, mult(&num1, &num2));

    }else if(op == '/')
    {
    printf("\n%d / %d = %f\n", num1, num2, div(&num1, &num2));

    }else if(op == '-')
    {
        printf("\n%d - %d = %d\n", num1, num2, sub(&num1, &num2));

    }else if (op == '+')
    {
        printf("\n%d + %d = %d\n", num1, num2, soma(&num1, &num2));

    }else
    {
        printf("\nOperacao invalida\n");

    }


    return 0;
}

What is happening and why does one pointer differ from the other if they are implemented in the same way?

    
asked by anonymous 06.04.2017 / 20:21

2 answers

3

The accounts in their functions are wrong. You should use +, -, *, / instead of + =, - =, * = and /=.

And I believe the error happens when the program tries to read the character of the operation. The correct would be:

scanf(" %c", &op); //com espaço antes do %c

Note: why are you using printf and scanf instead of std :: cout and std :: cin?

    
06.04.2017 / 22:43
0

You are putting the result of the value of your operations in num1 .

What you're doing is similar to:

int num1 = 0;
int num2  = 5;
num1 += num2; 

Now the value of num1 is the result of the operation: 5.

What you want is return num1 + num2 or in pointer dereferencing: return *a + *b . What returns the sum of the values and does not add the variable num1 to the result.

Just remove = from operations.

Also note that although the function returns float you must explicitly convert the values to float in your split.

float div(int *a, int *b)
{
    return (float)*a / (float)*b;
}
    
06.04.2017 / 22:55