Re: Subtract smaller or larger number from x?
- From: Steve O'Hara-Smith <steveo@xxxxxxxxxx>
- Date: Wed, 29 Mar 2006 14:53:40 +0100
On 29 Mar 2006 05:39:29 -0800
upeksharuvani@xxxxxxxxx wrote:
eksamor@xxxxxxxxx wrote:
I have a number x. I would now like to find the difference between this
number x and another number y.
But y can be either larger or smaller than x. Currently I check if the
number y is greater or smaller than x:
int diff; // the difference between x and y
if (y > x){
diff = y-x;
}else{
diff = x-y;
}
is there not a more elegant way to do this when I would like the
difference to be a positive value??
Yes, of course
As my sis pointed out it would be more efficient if you take the
absolute value of the differenc, like this:
And then again it might not be more efficient - consider the
function call overhead and observe that the source code for abs looks like
this:
int
abs(int j)
{
return(j < 0 ? -j : j);
}
So in addition to doing the subtraction and a test it is doing a
function call and perhaps a negation - whereas the original is doing a test
and a subtraction. Seems pretty certain to be less efficient to me.
This version might be more efficient but I doubt it, it probably
compiles to pretty much the same code as the original. It is perhaps a
little prettier.
diff = (y > x) ? y - x : x - y;
--
C:>WIN | Directable Mirror Arrays
The computer obeys and wins. | A better way to focus the sun
You lose and Bill collects. | licences available see
| http://www.sohara.org/
.
- Follow-Ups:
- Re: Subtract smaller or larger number from x?
- From: Gerry Quinn
- Re: Subtract smaller or larger number from x?
- From: robertwessel2@xxxxxxxxx
- Re: Subtract smaller or larger number from x?
- References:
- Subtract smaller or larger number from x?
- From: eksamor
- Re: Subtract smaller or larger number from x?
- From: upeksharuvani
- Subtract smaller or larger number from x?
- Prev by Date: Re: Subtract smaller or larger number from x?
- Next by Date: Re: Checking for Modification to a Set of Files
- Previous by thread: Re: Subtract smaller or larger number from x?
- Next by thread: Re: Subtract smaller or larger number from x?
- Index(es):
Relevant Pages
|