2
I have the task of creating four functions that do multiplication, division, sum and subtraction between two numbers given by the user. The operation to be performed must be chosen through the * / - +characters, given by the user.
I must use pointers to do the operations, the pointer to the first number works well, but the second, when you enter 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 one pointer differs from the other if they are implemented in the same way?
Why do you do
return *a *= *b
instead ofreturn *a * *b
. You need the first argument to contain the result when returning from the function?– Pagotti
Hello, I just need to return the result. I tried it the way
return *a * *b
but the second pointer continues at 0.– Rodrigo Souza