蓝桥杯 ADV-222 求arccos

蓝桥杯 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>1e5,最后得到的 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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值