C++程式:查詢給定弧度值的正弦值


正弦是一個與直角三角形相關的三角引數。正弦是對邊與斜邊的比值。在計算正弦時,我們需要知道斜邊與對邊之間的角度。假設該角度為𝜃。sin(𝜃)如下所示:

$$\mathrm{sin(\theta)\:=\:\frac{對邊}{斜邊}}$$

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

sin() 函式

為了計算sin(𝜃),我們需要使用cmath庫中的sin()方法。此函式以弧度為單位接收角度,並直接返回結果。語法很簡單,如下所示:

語法

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

演算法

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

示例

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

輸出

The value of sin( 2.5 ) is: 0.598472
The value of sin( 3.14159 ) is: 2.53518e-06
The value of sin with an angle of 30 degrees is: 0.5
The value of sin with an angle of 45 degrees is: 0.707106

在這個例子中,對於前兩個輸入,我們給出了弧度值,對於後兩個,角度以度為單位給出,但使用以下公式轉換為弧度

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

結論

C++中的sin$(\theta)$函式用於獲取給定弧度單位𝜃的sin$(\theta)$值。此函式是一個標準庫函式,但要使用它,我們需要在C++程式碼中包含cmath標頭檔案。根據C++的版本,C90版本返回型別為double,但在後續版本中,函式針對float、long double進行了過載,並在高階用法中針對整數型別使用泛型(模板)。在本文中,我們使用此函式,並傳入了一些不同的引數,以弧度或度為單位,但對於度,值使用上述公式轉換為弧度。

更新於: 2022年10月17日

552 次瀏覽

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告