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:
- Syntax: double fabs(double x)
- Parameter: x is a floating point number for which the absolute value is to be calculated.
- The return value of the fabs() function is a non-negative double value, which is the absolute value of the parameter x.
- Header file: You need to include the
header file to use the fabs() function. - 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.