Open In App

acos() function in C++ STL

acos() is an inbuilt function in C++ STL and it’s the same as the inverse of cosine in maths. The acos() function returns the values in the range of [0, π] which is the angle in radians.

Syntax

acos(data_type x);

Parameters

Note: x must be in the range of [-1, 1] to find valid output as [0, π], else acos(x) function returns NaN(Not a Number).



Return Value

Examples of acos() function

Example 1:

The below C++ program demonstrates the usage of the acos() function.




// C++ program to demonstrate
// the acos() function
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    double x = 1.0;
 
    // Function call to calculate acos(x) value
    double result = acos(x);
 
    cout << "acos(1.0) = " << result << " radians" << endl;
    cout << "acos(1.0) = " << result * 180 / 3.141592
         << " degrees" << endl;
 
    return 0;
}

Output

acos(1.0) = 0 radians
acos(1.0) = 0 degrees

Example 2:

The below C++ program demonstrates the usage of the acos() function.




// C++ program to demonstrate
// the acos() function
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    double result;
    int x = -1;
 
    // Function call to calculate acos(x) value
    result = acos(x);
 
    cout << "acos(-1) = " << result << " radians" << endl;
    cout << "acos(-1) = " << result * 180 / 3.141592
         << " degrees" << endl;
 
    return 0;
}

Output
acos(-1) = 3.14159 radians
acos(-1) = 180 degrees

Errors and Exceptions in acos()

Example 3:

The below C++ program shows the error that occurred when a string is passed as an argument to acos() function.




// C++ program to demonstrate the acos()
// function errors and exceptions
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    double result;
    string x = "gfg";
    result = acos(x);
 
    cout << "acos(x) = " << result << " radians" << endl;
    cout << "acos(x) = " << result * 180 / 3.141592
         << " degrees" << endl;
 
    return 0;
}

Output

prog.cpp:10:20: error: no matching function for call to 'acos(std::string&)'
     result = acos(x);

Example 4:

The below C++ program demonstrates the usage of the acos() function when arguments are x >1 or x<-1, it will give nan(not a number).




// C++ program to demonstrate the
// acos() function errors and exceptions
#include <bits/stdc++.h>
using namespace std;
 
int main()
{
    double x = 3.7, result;
 
    // Function call to calculate acos(x) value
    result = acos(x);
 
    cout << "acos(3.7) = " << result << " radians" << endl;
    cout << "acos(3.7) = " << result * 180 / 3.141592
         << " degrees" << endl;
 
    return 0;
}

Output
acos(3.7) = nan radians
acos(3.7) = nan degrees

Time Complexity: O(1)
Auxiliary Space: O(1)


Article Tags :
C++