Java实现 蓝桥杯 算法提高 求arccos值

算法提高 7-2求arccos值
时间限制:10.0s 内存限制:256.0MB
提交此题
问题描述
  利用标准库中的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。

import java.util.Scanner;


public class 求arccos值 {
	  public final static double PI = Math.PI;

	    public static void getArcCos(double x) {
	        double i = 0, j = PI;
	        double result = (i + j) / 2;
	        double judge = Math.cos(result) - x;
	        double temp;
	        while(Math.abs(judge) > 0.000000000000001) {
	            result = (i + j) / 2;
	            temp = Math.cos(result);
	            if(temp - x > 0) {  
	                i = result;
	            } else {
	                j = result;
	            }
	            judge = Math.cos(result) - x;
	            
	        }
	        System.out.printf("%.5f", result);
	        return;
	    }
	    
	    public static void main(String[] args) {
	       
	        Scanner in = new Scanner(System.in);
	        double x = in.nextDouble();
	        if(x < -1 || x > 1)
	            return;
	        getArcCos(x);
	    }

}

原文地址:https://www.cnblogs.com/a1439775520/p/12948679.html