Click to See Complete Forum and Search --> : How Do You?


Ercan
March 30th, 1999, 04:47 AM
How do you write a code in C++ that gives you the difference between

2 numbers. For example: 1 and 9 the difference is 8.

Now I know you can say 9-1=8 but 1-9= -8. What I need is the difference

without going into minus.... I find this very hard and cant find how the

logic of the code should be or even how to write it....

How do you write the code for that. I am new to this so I need the

most basic code.

Thank You in Advance...

Ercan

Martin Speiser
March 30th, 1999, 05:00 AM
Hi Ercan,


take a look at the abs function (for int), labs (for long int) or fabs (for float).


HTH


Martin

Ercan
March 30th, 1999, 05:09 AM
I dont understand what you mean Martin. I have not heard abs function or

labs or fabs. I have not seen or used them yet so I dont understand.

Is there another more basic way of writting this code. I know there must

be easier ways of doing it but i have not been tought how yet so i cant

use them.....

If you know of an easier way using simple code them please let me know.

If not

I thank you for responding. It feels good when somebody actually responds.

Thank You again

Ercan

Daren Chandisingh
March 30th, 1999, 05:17 AM
All of the abs functions give you the "absolute" value of

a quantity - that is the numerical amount without regard to

its sign. To get that amount, use code such as:


int x = 9;

int y = 1;


int iAbs = abs(y-x); // iAbs equals 8

Ercan
March 30th, 1999, 05:24 AM
Thank you all for responding. YOu guys have been a great help to me.

Now i doont have to pull my hair out anymore... hehehe


Thank You again.

Ercan

Dave Lorde
March 30th, 1999, 05:25 AM
Ercan,


abs, labs, and fabs are functions provided with the compiler to do exactly what you asked for. Abs is short for absolute, and they will convert a number to its absolute value, so that negative numbers become positive.


These functions can be found in stdlib.h or math.h


You can do the work yourself, but it's just simple maths:


int x = someValue();


if (x < 0)

x = -x;


The functions in the libraries provided with the compiler are there to save you writing your own code to do these things. Look them up in the documentation provided and use them wherever you can, they are safe and efficient.


Dave

deep
March 30th, 1999, 06:22 AM
int x ,y,z;

z = sign(x - y)*(x - y);


deep

Alvaro
March 30th, 1999, 07:52 AM
How about:


int x = 1;

int y = 9;

int diff = ((x > y) ? (x - y) : (y - x));

indika
March 30th, 1999, 07:54 AM
easy as 123..