fabs() in C++ (original) (raw)

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:

Return:

Error:

# CODE 1

CPP `

// CPP code to illustrate // fabs() function #include #include

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 `

// CPP code to illustrate // fabs() function #include #include

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 #include

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 #include #include 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)