Simple question. Reviewing

This program works and im trying dissect in and understand. But for love of God I cannot figure out why the value returned is 1214 and not -1. I'm sure returning the abs is the cause, but I can't figure out why. A brief explanation will suffice or a link to where I can read up on it.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
  #include <iostream>
#include <cstdlib>
using namespace std;


int difference(const int x, const int y)
{
    return abs(x - y);
}

int main(int argc, const char *argv[])
{
    cout << difference(24, 1238) << endl;
    return 0;
}

Why must the difference be -1?
Are you blaming your computer?
closed account (E0p9LyTq)
You might want to review what the C library abs() function does to help you understand the output.

http://www.cplusplus.com/reference/cstdlib/abs/
no no, before instead of

"return abs(x -y);

It was " int diff = abs (x - y)" which would always output -1. But after changing it to the above code it outputted the correct value. I'm trying to understand WHY that is.

and no, I wasn't.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//This function finds the difference of x & y
// and returns an absolute value, so it won't be negative.
int difference(const int x, const int y)
{
    return abs(x - y);
}

int main(int argc, const char *argv[])
{
    //This calls the difference function with values x = 24, y = 1238
    // 24 - 1238 = -1214
    // abs(-1214) = 1214. Therefore it should return 1214 and not -1
    cout << difference(24, 1238) << endl;
    return 0;
}
thank you.
Topic archived. No new replies allowed.