C++ sin() function [3 Examples]
The sin function in C++
- sin() is the built-in function in C++
- This function is defined in the <cmath> library – you have to include this in the header in order to use it.
- The sin() function takes one argument i.e. a number which is angle and it returns the sine of angle x radians.
- The return value is of double type i.e. sine of the given argument x (radians)
Syntax of sin() function
sin(x);
An example of using sin() function
In the first example, we simply provide a value to the sin() function and assign the return value to a double-type variable. Then we displayed the result as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include <iostream> #include<cmath> using namespace std; int main() { //angle in radians double ang=1.04; cout<<"Sine of an 1.04 = "<<sin(ang) <<"\n\n"; return 0; } |
Result:
Taking user input for sin()
As you run this C++ program, it asks you to enter the angle given in radians. Then sin() function is used to get the sine and we will display the result:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
#include <iostream> #include<cmath> using namespace std; int main() { //angle in radians double ang; cout << "Enter angle (in radians) to get sine : "; cin >> ang; cout<<"Sine of " <<ang <<"= " <<sin(ang) <<"\n\n"; return 0; } |
Sample result:
Using negative value example
For this example, we assigned a negative value to the sin() function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
#include <iostream> #include<cmath> using namespace std; int main() { //negative angle double ang = -45; //angle to radians double rad=ang*3.14/180; //Using radian in sin() function cout<<"Sine of " <<rad <<" = " <<sin(rad); return 0; } |
Output: