C 庫 - acos() 函式



C 庫的 acos() 函式返回x的反餘弦值(以弧度為單位)。

此引數必須在 -1 到 1 的範圍內,如果給定的輸入超出範圍,它將返回 nan 並可能將 errno 設定為 EDOM。

語法

以下是 C 庫 acos() 函式的語法:

double acos(double x)

引數

此函式只接受一個引數:

  • x - 這是區間 [-1,+1] 內的浮點值。

返回值

此函式返回 x 的主值反餘弦,在區間 [0, pi] 弧度內,否則返回 nan(非數值)的值。

示例 1

以下是一個基本的 C 庫程式,用於演示 acos() 函式。

#include <stdio.h>
#include <math.h>

#define PI 3.14159265

int main () {
   double x, ret, val;

   x = 0.9;
   val = 180.0 / PI;

   ret = acos(x) * val;
   printf("The arc cosine of %lf is %lf degrees", x, ret);
   
   return(0);
}

輸出

以上程式碼產生以下結果:

The arc cosine of 0.900000 is 25.855040 degrees

示例 2

以下程式說明了 acos() 的用法,其中引數 x > 1 或 x < -1,它將返回 nan 作為結果。

#include <stdio.h>
#include <math.h>

int main()
{
   double x = 4.4, res;

   // Function call to calculate acos(x) value
   res = acos(x);

   printf("acos(4.4) = %f radians\n", res);
   printf("acos(4.4) = %f degrees\n", res * 180 / 3.141592);

   return 0;
}

輸出

執行以上程式碼後,我們將得到以下結果:

acos(4.4) = nan radians
acos(4.4) = nan degrees

示例 3

在這裡,我們設定宏在 1 到 -1 之間的數值範圍內,以檢查給定的數字是否存在於範圍內。

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
 
#define MAX  1.0
#define MIN -1.0
 
int main(void)
{
   double x = 10, y = -1; 
   
   y = acos(x);
   if (x > MAX)
     printf( "Error: %lf not in the range!\n", x );
   else if (x < MIN)
     printf( "Error: %lf not in the range!\n", x );
   else 
     printf("acos(%lf) = %lf\n", x, y);
}

輸出

執行以上程式碼後,我們將得到以下結果:

Error: 10.000000 not in the range!
廣告