C++ Program to find the cosine of given radian value


Cosine is a trigonometric term that deals with right-angled triangle. When an acute angle is thought of as being a member of a right triangle, the cosine trigonometric function measures the distance between the angle's neighbouring leg and the hypotenuse. We require the angle between the hypotenuse and the adjacent edge in order to calculate cosine. Let the angle is 𝜃. The cos$(\theta)$ is like below

$$\mathrm{cos(\theta)\:=\:\frac{adjacent}{hypotenuse}}$$

In this article, we shall discuss the techniques to get the value of cos$(\theta)$ in C++ when the angle is given in the radian unit.

The cos() function

To compute the cos$(\theta)$ The cmath library's cos() method must be used. This function accepts an angle in radians and outputs the value immediately. Simple syntax is used here −

Syntax

#include < cmath >
cos( <langle in radian> )

Algorithm

  • Take angle x in radian as input.
  • Use cos( x ) to calculate the cos (𝑥).
  • Return result..

Example

#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; }

Output

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

In this example, the first two inputs have values in radians, while the last two inputs contain angles in degrees that have been transformed into radians using the formula below.

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

Conclusion

Get the cos value for the specified angle in the radian unit in C++ using the cos() method. Although this function is a part of the standard library, we must include the cmath header file in our C++ code in order to utilise it. According to the versions of C++, the C90 version had a return type of double, while later versions have overloaded functions for float and long double, as well as enhanced usage of generic (template) for integral types. This function has been used in this article with a variety of parameters in either radians or degrees; however, for degrees, the values are transformed into radians using the formula shown above.

Updated on: 17-Oct-2022

284 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements