What is the purpose of the fabs function in C++?

fabs() is a mathematical function in the C++ standard library used to calculate the absolute value of a floating-point number. Here are some details about the fabs() function:

  1. Syntax: double fabs(double x)
  2. Parameter: x is a floating point number for which the absolute value is to be calculated.
  3. The return value of the fabs() function is a non-negative double value, which is the absolute value of the parameter x.
  4. Header file: You need to include the header file to use the fabs() function.
  5. Note: The fabs() function is only applicable to floating point numbers. If you need to calculate the absolute value of an integer, you can use the abs() function.

For example, in a C++ program, the fabs() function is used as shown below:

#include <iostream>
#include <cmath>

int main() {
    double num = -7.89;
    double abs_num = fabs(num);

    std::cout << "The absolute value of " << num << " is: " << abs_num << std::endl;

    return 0;
}

The code above will produce:

The absolute value of -7.89 is: 7.89

The fabs() function can easily be used to obtain the absolute value of a floating point number, without considering its positive or negative sign.

广告
Closing in 10 seconds
bannerAds