Unlock the Power of Absolute Values in C++

The Basics of fabs()

Defined in the <cmath> header file, fabs() is a mathematical function that takes a single parameter: a floating-point number. This number can be of type double, float, or long double. The function’s syntax is straightforward: fabs(num). But what does it do, exactly? Simply put, fabs(num) equals |num|, or the absolute value of the input number.

Understanding the Return Value

So, what can you expect from the fabs() function? The answer is simple: it returns the absolute value of the input number. This means that if you pass a negative number, fabs() will return its positive equivalent. For example, fabs(-5) would return 5.

Prototypes and Variations

The <cmath> header file defines two prototypes for fabs(): one for double and one for long double. But here’s a little-known fact: fabs() is identical to fabs(). This means you can use either function interchangeably, depending on your coding style and preferences.

Putting fabs() to the Test

Let’s see fabs() in action with a few examples.

Example 1: Floating-Point Number


#include <iostream>
#include <cmath>

int main() {
    double num = -3.5;
    std::cout << "Absolute value of " << num << " is " << fabs(num) << std::endl;
    return 0;
}

The output? Absolute value of -3.5 is 3.5.

Example 2: Integral Type


#include <iostream>
#include <cmath>

int main() {
    int num = -10;
    std::cout << "Absolute value of " << num << " is " << fabs(num) << std::endl;
    return 0;
}

The output? Absolute value of -10 is 10.

With fabs() in your coding toolkit, you’ll be better equipped to handle a wide range of mathematical challenges in C++.

Leave a Reply