Difference between fabs and abs function in C++
In this tutorial, let’s study the difference between fabs and abs function in C++.
Fabs() and abs() functions are almost identical and are included in <cmath> header file in C++ language.
The difference between the fabs() and abs() function is that fabs() function is used for floating values and abs() function is used for integer values.
abs() function
abs() function returns the absolute value for the integer.
Example 1
#include <iostream> #include <cmath> using namespace std; int main() { cout << fabs(-64) << "\n"; return 0; }
Output
64
Example 2
#include <iostream> #include <cmath> using namespace std; int main() { int num = -34; cout << abs(num) << "\n"; return 0; }
Output
34
fabs() function
fabs() function returns the absolute value of the floating number.
Example 1
#include <iostream> #include <cmath> using namespace std; int main() { cout << fabs(-64.89) << "\n"; return 0; }
Output
64.89
Example 2
#include <iostream> #include <cmath> using namespace std; int main() { float num = -34.98; cout << abs(num) << "\n"; return 0; }
Output
34.98
Note:
We can also use the abs() and fabs() function for other data types such as double, long including int, and float.
Please change the answer example number 2
example numbe 2 answer is 34.98
Thanks for your comment, we have updated the answer. Cheers!