Math Fabs Function - C++ Programming Tutorial
C++ Course / Math Functions / Math Fabs Function

Math Fabs Function

BLUF: Mastering Math Fabs Function is a critical step in becoming a proficient C++ developer. This lesson provides a deep dive into the syntax, performance considerations, and real-world applications of this concept.
Key Performance Insight: Math Fabs Function

C++ is renowned for its efficiency. Learn how Math Fabs Function enables low-level control and high-performance computing in the tutorial below.

C++ Math fabs

It computes the absolute value of a given number.

Suppose a number is 'x' :

Example

fabs(x) = |x|;

Syntax

Example

float fabs(float x);
double fabs(double x);
int fabs(int x);

Parameter

x : The value for which we need to find the absolute value.

Return value

It returns the absolute value of x.

Example 1

Let's examine a straightforward scenario where the value of x is greater than zero.

Example

#include <iostream>
#include<math.h>
using namespace std;
 int main()
{
float x=11.2;
 std::cout << "Value of x is :" <<x<< std::endl;
 cout<<"Absolute value of x is : "<<fabs(x);
 return 0;
}

Output:

Output

Value of x is :11.2
Absolute value of x is : 11.2

In this instance, the fabs method calculates the absolute magnitude of x=11.2.

Example 2

Let's consider a basic scenario where the value of x is below zero.

Example

#include <iostream>
#include<math.h>
using namespace std;
int main()
{
   float x=-9.4;
   std::cout << "Value of x is :" <<x<< std::endl;
   cout<<"Absolute value of x is : "<<fabs(x);
    return 0;
}

Output:

Output

Value of x is :-9.4
Absolute value of x is : 9.4

In this instance, the fabs function calculates the absolute value of x when x is -9.4.

Input Required

This code uses input(). Please provide values below:

Logic Practice
Install Logic Practice
Add to home screen for a faster app-like experience