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