Solved

# Absolute Value

Posted on 2000-03-14
207 Views
How do you find the absolute value of a number, any number
0
Question by:SBuntin

LVL 1

Expert Comment

ID: 2617238
what do you mean by absolute?
0

Expert Comment

ID: 2617325
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?
0

LVL 1

Accepted Solution

Binder earned 20 total points
ID: 2617330
If the number is an integer use

absolute = abs(number);

If the number is long use

absolute = labs(number);

If the number is float use

absolute = fabs(number);
0

LVL 10

Expert Comment

ID: 2619803
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).

0

LVL 10

Expert Comment

ID: 2621545
guess you didn't want the general single solution that works for any number :-(
0

## Featured Post

This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
This article shows you how to optimize memory allocations in C++ using placement new. Applicable especially to usecases dealing with creation of large number of objects. A brief on problem: Lets take example problem for simplicity: - I have a G…
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.
The viewer will be introduced to the member functions push_back and pop_back of the vector class. The video will teach the difference between the two as well as how to use each one along with its functionality.