acos()是C++ STL中的内置函数,该函数返回弧度数(参数)的反余弦值。 acos()函数返回的值始终位于–
到+
用法:
acos(data_type x)
参数:此函数接受一个强制性参数x,该参数指定应计算其反余弦值的值。它必须介于-1和+1之间,否则将抛出域错误(范围错误)。该参数可以是double,float或long double数据类型。
返回:该函数返回介于–
和+
。逆时针角度以弧度为单位。
示例1:
// C++ program to demonstrate
// the acos() function
#include
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;
}
输出:
acos(1.0) = 0 radians
acos(1.0) = 0 degrees
示例2:
// C++ program to demonstrate
// the acos() function
#include
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;
}
输出:
acos(-1) = 3.14159 radians
acos(-1) = 180 degrees
错误和异常:
当字符串或字符作为参数传递时,该函数不返回任何匹配函数来调用错误。
当传递超出范围的数字作为参数时,该函数将返回nan。
以下示例程序旨在说明上述方法的错误和异常:
示例3:
// C++ program to demonstrate the acos()
// function errors and exceptions
#include
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;
}
输出:
prog.cpp:10:17: error: no matching function for call to 'acos(std::__cxx11::string&)'
result = acos(x);
示例4:
// C++ program to demonstrate the
// acos() function errors and exceptions
#include
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;
}
输出:
acos(3.7) = nan radians
acos(3.7) = nan degrees