一、要求
利用标准库中的cos(x)和fabs(x)函数实现arccos(x)函数,x取值范围是[-1, 1],返回值为[0, PI]。要求结果准确到小数点后5位。(PI = 3.1415926)
输入:
一个数x
-1 <= x <= 1, 0 <= arccos(x) <= PI。
输出:
计算后的结果
二、分析
二分法
第一次[0,pi],再慢慢缩小范围,直到精度<0.000001
三、代码
#include <iostream>
#include<math.h>
using namespace std;
#define pi 3.1415926 //注意格式,没有等号!没有分号!
#define minn 0.000001
double n;
double twofen(double l, double h) {
if (h - l < minn) return l;
double result = (l + h) / 2;
if (cos(result) > n) return twofen(result, h);
else if (cos(result) == n) return result;
else if(cos(result) < n) return twofen(l,result);
}
int main() {
cin >> n;
printf("%.5lf", twofen(0, pi));
return 0;
}