fabs() in C++
Last Updated :
31 Jan, 2023
The fabs() function returns the absolute value of the argument. Mathematically |a|. If a is value given in the argument. Syntax:
double fabs(double a);
float fabs(float a);
int fabs(int a);
Parameter:
- The fabs() function takes a single argument, a whose absolute value has to be returned.
Return:
- The fabs() function returns the absolute value of the argument.
Error:
- It is mandatory to give both the arguments otherwise it will give error no matching function for call to ‘fabs()’ like this.
# CODE 1
CPP
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
int a = -10, answer;
answer = fabs (a);
cout << "fabs of " << a
<< " is " << answer << endl;
return 0;
}
|
OUTPUT :
fabs of -10 is 10
Time Complexity: O(1)
Space Complexity: O(1)
# CODE 2
CPP
#include <cmath>
#include <iostream>
using namespace std;
int main()
{
long int a = -35;
double answer;
answer = fabs (a);
cout << "fabs of " << a << " is "
<< answer << endl;
return 0;
}
|
OUTPUT :
fabs of -35 is 35
Time Complexity: O(1)
Space Complexity: O(1)
Here is an example of a double.
#Code 3
C++
#include <cmath>
#include <iostream>
using namespace std;
int main() {
double x = -3.14;
cout << "The absolute value of " << x << " is " << fabs (x) << endl;
return 0;
}
|
Output
The absolute value of -3.14 is 3.14
Time Complexity: O(1)
Space Complexity: O(1)
#Code 4
C++
#include <cmath>
#include <iostream>
#include <string>
using namespace std;
int main() {
double x = -5.67;
cout << "The absolute value of " << x << " is " << fabs (x) << endl;
string s = to_string( fabs (x));
cout<< "The absolute value of " <<x<< " is string format: " <<s<<endl;
return 0;
}
|
Output
The absolute value of -5.67 is 5.67
The absolute value of -5.67 is string format: 5.670000
Time Complexity: O(1)
Space Complexity: O(1)
Share your thoughts in the comments
Please Login to comment...