Absolute value functions abs() fabs()
Using absolute value functions like fabs() and abs().
Learning Objectives
- Use of fabs() and abs() to find the absolute or sign omitted value of any number.
Source Code
|
|
Run Output
Code Understanding
double a=-7.32;
This variable is to be used as input to the absolute value functions.
cout<<“fabs(“<<a<<“) = “<<fabs(a)<<endl;
The function fabs() is useful for finding absolute value of fractional inputs like float and double. Here -7.32 will become 7.32 as for finding absolute value the sign is omitted.
cout<<“abs((int)”<<a<<“) =”<<abs((int) a)<<endl;
The abs() function is meant for finding absolute value of integer data types. So in this example the fractional value stored in a has been first typecasted to an integer and then abs has been found. After (int) typecasting of -7.32 it will become -7 and then absolute value will be just 7
Notes
- If cmath library is used in place of math.h both fabs() and abs() function behave in the same way as abs() function in that case can also handle the float/double input with suitable overloading.
Suggested Filename(s): math-abs.cpp
Created: 3-Jan-2018 18:09 | Updated: 13-Jan-2018 03:05|
