SBuntin
asked on
Absolute Value
How do you find the absolute value of a number, any number
what do you mean by absolute?
Are you looking for the non-fractional part of a number? You can cast a floating point number to an integral type.
double x = 9999.999;
int getAbsolute(double n){
return (int)n;
}
If you pass x to getAbsolute, it returns 9999. It couldn't be that simple, I assume there's a bit more to what you're trying to do. Can you elaborate on the question?
double x = 9999.999;
int getAbsolute(double n){
return (int)n;
}
If you pass x to getAbsolute, it returns 9999. It couldn't be that simple, I assume there's a bit more to what you're trying to do. Can you elaborate on the question?
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
For any number, do something like this
template <typename T> inline T ABS(T t) {
return -t < t ? t : -t;
}
In fact, this works for ANY type for which '<' and unary '-' are defined
(This is superior to return t<0?-t:t as it does not require a comparison with the number zero).
template <typename T> inline T ABS(T t) {
return -t < t ? t : -t;
}
In fact, this works for ANY type for which '<' and unary '-' are defined
(This is superior to return t<0?-t:t as it does not require a comparison with the number zero).
guess you didn't want the general single solution that works for any number :-(