fabs function in C

The fabs function in C computes the absolute value of a floating-point number x. The x is the argument that is passed into the fabs().

It is declared in math.h and takes one argument in the form of double and returns the value of type double.

Example,

Input : 3.5
Output : 3.5


Input : -2.6
Output : 2.6


Input : -5.9
Output : 5.9

 

Syntax of fabs function in C:

//syntax of fabs function in c

double fabs(double x);

Parameters:

x => floating types (double)

Return value:

The fabs functions return |x|.

 

You can use the fabsf() function to work specifically with float and fabsl() to work with long double type. See the below syntax.

//Syntax of other fabs function in C

float fabsf(float x);

long double fabsl(long double x);

 

 

C program to understand the working of fabs function:

Below mentioned C example code shows the usage of fabs().

#include <stdio.h>
#include <math.h>

int main()
{
    double x, result;

    x = 3.5;
    result = fabs(x);
    printf("|%.2lf| =  %.2lf\n", x, result);

    x = -2.6;
    result = fabs(x);
    printf("|%.2lf| =  %.2lf\n", x, result);

    x = -5.9;
    result = fabs(x);
    printf("|%.2lf| =  %.2lf\n", x, result);

    return 0;
}

Output:

|3.50| = 3.50
|-2.60| = 2.60
|-5.90| = 5.90

 

Error handling

This function is not subject to any of the error conditions specified in math_errhandling.

If the implementation supports IEEE floating-point arithmetic (IEC 60559),

  • If the argument is ±0, +0 is returned.
  • If the argument is ±∞, +∞ is returned.
  • If the argument is NaN, NaN is returned.
#include <stdio.h>
#include <math.h>

int main()
{
    printf("fabs(-0) = %f\n", fabs(-0.0));
    printf("fabs(-Inf) = %f\n", fabs(-INFINITY));

    return 0;
}

Output:

fabs(-0) = 0.000000
fabs(-Inf) = inf

 

Recommended Post:

Leave a Reply

Your email address will not be published. Required fields are marked *