What is the usage of the absolute value function in C++…

The absolute value function in C++ is used to calculate the absolute value of a number. The absolute value is the non-negative value of a number, if the number is positive or zero, then its absolute value is itself; if the number is negative, then its absolute value is the negative of itself.

There are two commonly used absolute value functions in C++: abs() and fabs().

  1. The abs() function is used to calculate the absolute value of an integer, with its function prototype as follows:
int abs(int n);

Example of Usage:

#include <iostream>
#include <cstdlib>

int main() {
    int num = -10;
    int result = abs(num);
    std::cout << "The absolute value of " << num << " is " << result << std::endl;
    return 0;
}

Output result:

The absolute value of -10 is 10
  1. fabs() function: This function is used to calculate the absolute value of a floating-point number, and its function prototype is as follows:
double fabs(double n);

Example of use:

#include <iostream>
#include <cmath>

int main() {
    double num = -10.5;
    double result = fabs(num);
    std::cout << "The absolute value of " << num << " is " << result << std::endl;
    return 0;
}

The output is:

The absolute value of -10.5 is 10.5

It is important to note that the abs() function and fabs() function require the corresponding header files to be included. For integers, you can include the header file; for floating-point numbers, you can also include the header file.

bannerAds