蓝桥杯 ADV-222 求arccos
问题描述
利用标准库中的cos(x)和fabs(x)函数实现arccos(x)函数,x取值范围是[-1, 1],返回值为[0, PI]。要求结果准确到小数点后5位。(PI = 3.1415926)
提示:要达到这种程度的精度需要使用double类型。
样例输入
0.5
样例输出
1.04720
数据规模和约定
-1 <= x <= 1, 0 <= arccos(x) <= PI。
思路解析
我们知道
c
o
s
(
x
)
cos(x)
cos(x)与
a
r
c
c
o
s
(
x
)
arccos(x)
arccos(x)有以下对应关系:
c
o
s
(
y
)
=
x
,
a
r
c
c
o
s
(
x
)
=
y
cos(y) = x, \quad arccos(x) = y
cos(y)=x,arccos(x)=y
这道题中我们已知
x
x
x,可以通过二分查找来查找
y
y
y,使得
c
o
s
(
y
)
=
x
cos(y)=x
cos(y)=x,即通过不断缩小
y
y
y所在区间,直到满足精度
l
e
n
g
t
h
>
1
e
−
5
length>1e-5
length>1e−5,最后得到的
y
y
y 即是
a
r
c
c
o
s
(
x
)
arccos(x)
arccos(x)的近似值
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
int main() {
double x;
cin >> x;
double left = 0, right = 3.1415926;
while (fabs(right - left) > 1e-5){
double m = (left + right) / 2.0;
double res = cos(m);
if (res < x){
right = m;
}
else{
left = m;
}
}
cout << fixed << setprecision(5) << (left + right) / 2.0;
return 0;
}