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


類似於普通的三角函式,雙曲函式是使用雙曲線而不是圓來定義的。在雙曲幾何中,雙曲函式用於計算角度和距離。此外,它們也出現在許多線性微分方程、三次方程等的解中。對於給定的角度$\theta$,雙曲正切函式tanh$(\theta)$如下所示:

$$\mathrm{tanh(x)\:=\:\frac{sinh(x)}{cosh(x)}\:=\:\frac{e^{x}-e^{-x}}{e^{x}+e^{-x}}\:=\:\frac{e^{2x}-1}{e^{2x}+1}}$$

在本文中,我們將討論在給定以弧度為單位的角度時,如何使用C++獲取tanh$(\theta)$值的技術。

tanh() 函式

此tanh$(\theta)$運算需要C++ cmath庫中的tanh()函式。此函式以弧度為單位的角度作為輸入,並輸出雙曲餘弦值。以下是簡單的語法。

語法

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

演算法

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

示例

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

輸出

The value of tanh( pi/2 ) is: 0.917152
The value of tanh( pi ) is: 0.996272
The value of tanh with an angle of 90 degrees is: 0.917152
The value of tanh with an angle of 45 degrees is: 0.655794

此示例中的前兩個輸入數字以弧度為單位,而後兩個數字是使用以下公式轉換為弧度的度數:

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

結論

要在C++中計算給定以弧度為單位的角度的雙曲正切值,請使用tanh()函式。儘管它是標準庫的一部分,但為了使用此函式,需要在我們的C++程式碼中包含cmath標頭檔案。如果結果過大(根據x的值可能是正數或負數),tanh()函式將返回HUGE_VAL值並將錯誤程式碼設定為ERANGE。雖然C++的C90版本具有雙精度返回型別,但後來的C++版本除了更好地支援通用(模板)整型用法外,還為float和long double過載了方法。本文使用了多個此函式的引數,無論是弧度還是度數;但是,對於度數,其值使用上面給出的公式轉換為弧度。

更新於:2022年10月19日

瀏覽量:188

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.