C++程式:求給定弧度值的正切值


正切是三角學中關於直角三角形的概念。對於銳角,其三角函式是該角的對邊與鄰邊的比值,視為直角三角形。為了計算正切值,我們需要知道斜邊和鄰邊之間的夾角。設角度為𝜃。tan(𝜃)如下所示

$$\mathrm{tan(\theta)\:=\:\frac{對邊}{鄰邊}}$$

在本文中,我們將討論在C++中獲取以弧度為單位的角度的tan(𝜃)值的技術。

tan() 函式

為了計算tan(𝜃),必須使用cmath包中的tan()方法。此函式在接受以弧度表示的角度後立即輸出值。這裡使用了簡單的語法:

語法

#include < cmath >
tan( <angle in radian> )

演算法

  • 以弧度為單位輸入角度x。
  • 使用tan(x)計算tan(x)。
  • 返回結果。

示例

#include <iostream> #include <cmath> using namespace std; float solve( float x ) { float answer; answer = tan( x ); return answer; } int main() { cout << "The value of tan( 1.054 ) is: " << solve( 1.054 ) << endl; cout << "The value of tan( 3.14159 ) is: " << solve( 3.14159 ) << endl; cout << "The value of tan with an angle of 90 degrees is: " << solve( 90 * 3.14159 / 180 ) << endl; cout << "The value of tan with an angle of 45 degrees is: " << solve( 45 * 3.14159 / 180 ) << endl; }

輸出

The value of tan( 1.054 ) is: 1.75959
The value of tan( 3.14159 ) is: -2.53518e-06
The value of tan with an angle of 90 degrees is: 788898
The value of tan with an angle of 45 degrees is: 0.999999

本例中的前兩個輸入值以弧度為單位,而後兩個輸入值是以度為單位的角度,已使用以下公式轉換為弧度:

$$\mathrm{\theta_{rad}\:=\:\theta_{deg}\:\times\:\frac{\pi}{180}}$$

對於tan(90),其值為一個很大的整數,表示無窮大,因為tan(90°)未定義。

結論

C++中的tan()函式可用於獲取給定角度的以弧度表示的正切值。雖然此函式是標準庫的一部分,但要使用它,我們的C++程式碼必須包含cmath標頭檔案。C++的C90版本具有double返回型別,而更高版本則為float和long double以及改進的泛型(模板)整數型別用法提供了過載方法。本文中,此函式使用了以弧度或度為單位的各種引數;但是,對於度數,值使用上述公式轉換為弧度。

更新於:2022年10月17日

473 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告