Say you had a vector with some +ve ints and some -ve ints, how do you return the one which is closest to 0???
Printable View
Say you had a vector with some +ve ints and some -ve ints, how do you return the one which is closest to 0???
What's a +ve and -ve int?
vector meaning std::vector, or vector meaning those things in physics?
I haven't compiled this code, it's designed to give you an idea of the kind of thing you should be doing. It assumes there is at least one value in myVector.Code:#define ABS(x) ((x) < 0 ? -(x) : (x))
int GetClosestToZero(void)
{
int closest = myVector[0];
for(int i = 1; i < myVector.size(); i++)
{
if(ABS(myVector[i]) < ABS(closest))
{
closest = myVector[i];
}
}
return(closest);
}
U.
+ve = positive
-ve = negative
As someone has already asked, can you please clarify what you mean by 'vector'?Quote:
Originally posted by pdstatha
Say you had a vector with some +ve ints and some -ve ints, how do you return the one which is closest to 0???
Do you mean the mathematical construct (a one dimensional matrix) or do you mean std::vector??
std::vector that one
what do you mean by +ve and -ve ?
+ve = POSITIVE
-ve = NEGATIVE
or just read previous thread
Look at Uraldor's code.