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重载了函数,以及对整数类型使用泛型(模板)的增强用法。本文中此函数已使用各种参数(以弧度或度为单位)使用;但是,对于度,值使用上面显示的公式转换为弧度。

更新于: 2022年10月17日

390 次浏览

开启你的职业生涯

通过完成课程获得认证

立即开始
广告

© . All rights reserved.