Reputation: 33
In this code I am trying to output the sum and difference of two inputs. When I run this program, the sum outputs fine, but instead of the difference, the first input outputs. How can I make this program output the difference as well as the sum?
void Modify(int *x, int *y) {
*x = *x + *y;
if (*x >= *y)
*y = *x - *y;
if (*x < *y)
*y = *y - *x;
}
int main() {
int x, y;
int *ptr_x = &x;
int *ptr_y = &y;
cin >> x;
cin >> y;
Modify(ptr_x, ptr_y);
cout << x << endl;
cout << y;
return 0;
}
Upvotes: 1
Views: 278
Reputation: 10982
void Modify(int *x, int *y) {
*x = *x + *y;
if (*x >= *y)
*y = *x - *y;
if (*x < *y)
*y = *y - *x;
}
Your first line *x = *x + *y;
overwrites *x
value with *x + *y
, by consequence the next statements are misleading
if (*x >= *y)
*y = *x - *y;
if (*x < *y)
*y = *y - *x;
and are not performing what you expect.
As a general advice, keep your code simple and clear about your intends:
#include <cmath>
void Modify(int *x, int *y) {
using std::abs;
int sum = *x + *y;
int abs_diff = abs(*x - *y);
*x = sum;
*y = abs_diff;
}
Upvotes: 5
Reputation: 1409
This is not printing difference because you update the value of x
with the sum of both at *x = *x + *y
as @user4581301 suggested in the comment. You can do something like this.
void Modify(int *x, int *y) {
int* temp = new int(*x);
*x = *temp + *y;
if (*temp >= *y)
*y = *temp - *y;
if (*x < *y)
*y = *y - *temp;
delete temp;
}
What this will do is you will create an new integer pointertemp
will store the value of x
and now you can change x
but on other places where x
was needed we will use temp
instead of x. And at the end we are deleting the temp
.
Upvotes: 1
Reputation: 1166
It would be nice if you explain why you cannot do something simple as std::cout << x + y << endl << x - y;
without calling any function.
But if you want to do it that way, without extra variables, one option is this:
void Modify(int *x, int *y) {
*x = *x + *y; ///x = original x + original y
*y = *x - 2*(*y); ///y = (original x + original y) - 2*(original y)
}
Note: Be carefull with overflows
Edit: If you want absolute value of the difference, use instead *y = abs(*x - 2*(*y))
;
Upvotes: 2