C++ 中的三角函式
本文將講解如何在 C++ 中使用 STL 的三角函式。
在 C++ 中使用 std::sin
函式計算正弦
C++ 中的三角函式在標題 <cmath>
下提供。通常,常見的數學函式是從 C 語言繼承而來的,但其中大部分在 C++ 中被過載以與不同的引數型別互操作。
在這種情況下,我們表示 std::sin
函式來計算給定引數的正弦值。引數應該是一個以弧度為單位的值,如果函式成功,返回值在 [-1 ; +1]
。請注意,如果 std::sin
的值為 +-0
,則返回未修改的引數。
以下示例程式碼計算了常見角度的正弦值。
#include <iostream>
#include <cmath>
using std::cout; using std::endl;
const double pi = std::acos(-1);
int main() {
cout << "sin(pi) = " << std::sin(pi) << '\n'
<< "sin(pi/6) = " << std::sin(pi/6) << '\n'
<< "sin(pi/4) = " << std::sin(pi/4) << '\n'
<< "sin(pi/3) = " << std::sin(pi/3) << '\n'
<< "sin(pi/2) = " << std::sin(pi/2) << '\n'
<< "sin(+0) = " << std::sin(0.0) << '\n'
<< "sin(-0) = " << std::sin(-0.0) << '\n';
return EXIT_SUCCESS;
}
sin(pi) = 1.22465e-16
sin(pi/6) = 0.5
sin(pi/4) = 0.707107
sin(pi/3) = 0.866025
sin(pi/2) = 1
sin(+0) = 0
sin(-0) = -0
在 C++ 中使用 std::cos
函式計算餘弦
std::cos
是另一個核心三角函式,它與 std::sin
具有相似的特性,除了相同引數的返回值不同。請注意,所有三角函式都可以接受 angle 的值作為整數的浮點數,但相應的結果總是以浮點數返回。
#include <iostream>
#include <cmath>
using std::cout; using std::endl;
const double pi = std::acos(-1);
int main() {
cout << "cos(pi) = " << std::cos(pi) << '\n'
<< "cos(pi/6) = " << std::cos(pi/6) << '\n'
<< "cos(pi/4) = " << std::cos(pi/4) << '\n'
<< "cos(pi/3) = " << std::cos(pi/3) << '\n'
<< "cos(pi/2) = " << std::cos(pi/2) << '\n'
<< "cos(+0) = " << std::cos(0.0) << '\n'
<< "cos(-0) = " << std::cos(-0.0) << '\n';
return EXIT_SUCCESS;
}
cos(pi) = -1
cos(pi/6) = 0.866025
cos(pi/4) = 0.707107
cos(pi/3) = 0.5
cos(pi/2) = 6.12323e-17
cos(+0) = 1
cos(-0) = 1
使用 std::tan
函式計算給定弧度值的正切值
另一方面,我們有 std::tan
函式來計算給定引數的正切值。由於這些函式返回浮點值,因此可能會引發一些數學錯誤異常,這些異常在這裡有詳細描述。此外,我們還為每個三角函式提供了弧形版本,它們在原函式名稱中加入了 a
字首。
#include <iostream>
#include <cmath>
using std::cout; using std::endl;
const double pi = std::acos(-1);
int main() {
cout << "tan(pi) = " << std::tan(pi) << '\n'
<< "tan(pi/6) = " << std::tan(pi/6) << '\n'
<< "tan(pi/4) = " << std::tan(pi/4) << '\n'
<< "tan(pi/3) = " << std::tan(pi/3) << '\n'
<< "tan(pi/2) = " << std::tan(pi/2) << '\n'
<< "tan(+0) = " << std::tan(0.0) << '\n'
<< "tan(-0) = " << std::tan(-0.0) << '\n';
return EXIT_SUCCESS;
}
tan(pi) = -1.22465e-16
tan(pi/6) = 0.57735
tan(pi/4) = 1
tan(pi/3) = 1.73205
tan(pi/2) = 1.63312e+16
tan(+0) = 0
tan(-0) = -0
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn