|
-
March 30th, 1999, 05:47 AM
#1
How Do You?
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
-
March 30th, 1999, 06:00 AM
#2
Re: How Do You?
Hi Ercan,
take a look at the abs function (for int), labs (for long int) or fabs (for float).
HTH
Martin
-
March 30th, 1999, 06:09 AM
#3
Re:? I dont understand
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
-
March 30th, 1999, 06:17 AM
#4
Re:? I dont understand
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
-
March 30th, 1999, 06:24 AM
#5
Re:? Thank You all
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
-
March 30th, 1999, 06:25 AM
#6
Re:? I dont understand
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
-
March 30th, 1999, 07:22 AM
#7
more math
int x ,y,z;
z = sign(x - y)*(x - y);
deep
-
March 30th, 1999, 08:52 AM
#8
Re: How Do You?
How about:
int x = 1;
int y = 9;
int diff = ((x > y) ? (x - y) : (y - x));
-
March 30th, 1999, 08:54 AM
#9
Use abs() function - absolute value
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|