C++程式查詢給定弧度值的餘弦
餘弦是一個與直角三角形相關的三角函數術語。當銳角被認為是直角三角形的一部分時,餘弦三角函式測量該角的鄰邊與斜邊之間的距離。為了計算餘弦,我們需要知道斜邊和鄰邊之間的角度。假設該角為𝜃。cos$(\theta)$如下所示
$$\mathrm{cos(\theta)\:=\:\frac{鄰邊}{斜邊}}$$
在本文中,我們將討論當角度以弧度為單位給出時,在C++中獲取cos$(\theta)$值的技術。
cos() 函式
為了計算cos$(\theta)$,必須使用cmath庫中的cos()方法。此函式接受以弧度為單位的角度,並立即輸出其值。這裡使用簡單的語法:
語法
#include < cmath > cos( <langle in radian> )
演算法
- 以弧度為單位輸入角度x。
- 使用cos( x )計算cos (𝑥)。
- 返回結果。
示例
#include <iostream> #include <cmath> using namespace std; float solve( float x ) { float answer; answer = cos( x ); return answer; } int main() { cout << "The value of cos( 2.5 ) is: " << solve( 2.5 ) << endl; cout << "The value of cos( 3.14159 ) is: " << solve( 3.14159 ) << endl; cout << "The value of cos with an angle of 30 degrees is: " << solve( 30 * 3.14159 / 180 ) << endl; cout << "The value of cos with an angle of 45 degrees is: " << solve( 45 * 3.14159 / 180 ) << endl; }
輸出
The value of cos( 2.5 ) is: -0.801144 The value of cos( 3.14159 ) is: -1 The value of cos with an angle of 30 degrees is: 0.866026 The value of cos with an angle of 45 degrees is: 0.707107
在此示例中,前兩個輸入的值以弧度為單位,而後兩個輸入包含以度為單位的角度,這些角度已使用以下公式轉換為弧度。
$$\mathrm{\theta_{rad}\:=\:\theta_{deg}\times\:\frac{\pi}{180}}$$
結論
使用cos()方法在C++中獲取指定弧度單位角度的餘弦值。雖然此函式是標準庫的一部分,但為了使用它,我們必須在C++程式碼中包含cmath標頭檔案。根據C++的版本,C90版本的返回值型別為double,而更高版本則為float和long double過載了函式,以及對整數型別使用泛型(模板)的增強用法。本文中此函式已使用各種引數(以弧度或度為單位)使用;但是,對於度,值使用上面顯示的公式轉換為弧度。
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP