fabs() in C++



In C++, fabs is used to calculate the absolute value of a floating-point number. It is a function and defined to a <cmath> header file.

The fab() Function

This fabs() function accepts one argument, which is a floating-point number (double, float, or long double), and returns its absolute value as a floating-point number of the same type.

Syntax

Following is the syntax to fabs() function:

double fabs(double x); 

The fabs() function is mostly used when we need to find the non-negative magnitude of a number.

Using fabs() with positive and negative values

Here, we will demonstrate how fabs() handles both negative and positive values and ensure that the result will be always non-negative(positive).

Example

#include<iostream> #include<cmath> using namespace std; int main() { cout<<"fabs(-23.5) = "<< fabs(-23.5)<<endl; cout<<"fabs(7.1) = "<< fabs(7.1)<<endl; return 0; } 

Output

The above program produces the following result ?

fabs(-23.5) = 23.5 fabs(7.1) = 7.1 

Using fabs() with expressions

We use fabs() to arithmetic expressions, such as subtraction and multiplication for the absolute value of a floating point.

Example

In this example, we calculate the absolute values of two mathematical expressions using 'fabs()' function.

#include<iostream> #include<cmath> using namespace std; int main() { double result = fabs(3.5 - 9.8); cout<<"fabs(3.5 - 9.8) = "<<result<<endl; cout<<"fabs(-4.2 * 2.0) = "<< fabs(-4.2 * 2.0)<< std::endl; return 0; } 

Output

The program above produced the following outcome ?

fabs(3.5 - 9.8) = 6.3 fabs(-4.2 * 2.0) = 8.4 

Using fabs() in a Real-World Scenario (Temperature)

The fabs() function is used to compare the temperatures by ignoring whether they are above or below a reference point.

Example

In this example, we will calculate the absolute difference between actual and predicted temperatures using fabs():

#include<iostream> #include<cmath> // for fabs() using namespace std; int main() { double actual = 64.5; double predicted = 46.1; double difference = fabs(actual - predicted); cout<<"Actual Temperature: "<<actual<<"°C"<<endl; cout<<"Predicted Temperature: "<< predicted<<"°C"<<endl; cout<<"Absolute Temperature Difference: "<<difference<<"°C"<<endl; return 0; } 

Output

The program above produced the following outcome ?

Actual Temperature: 64.5°C Predicted Temperature: 46.1°C Absolute Temperature Difference: 18.4°C 
Updated on: 2025-04-29T11:32:37+05:30

613 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements