I am novice at programming in C++. I want to write a program using while loop which displays the trigonometric table for sin, cos and Tan. It takes angles in degrees with a difference of 5 and displays the result. This it what I tried,
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
int num;
cout<< "Angle Sin Cos Tan"<<endl;
cout<< "..........................."<<endl;
num=0;
while (num<=360)
{
cout <<setw(3)<<num<<" "
<<setw(3)<<setprecision(3)<<sin(num)<<" "
<<setw(3)<<setprecision(3)<<cos(num)<<" "
<<setw(5)<<setprecision(3)<<tan(num)<<endl;
num=num+5;
}
}
Unfortunately, I could not change radians into degrees in while loop and the display does not look promising even for radians. How can I resolve it ?
To convert degrees to radiant you have to multiply by pi and to divide by 180.0
:
#define M_PI 3.14159265358979323846
int num = 0;
while (num<=360)
{
double numRad = num * M_PI/180.0;
std::cout <<std::setw(3)<<num<<" "
<<std::setprecision(3)<<std::fixed
<<std::setw(6)<< std::sin( numRad ) <<" "
<<std::setw(6)<< std::cos( numRad ) <<" ";
if ( num != 90 && num != 270 )
std::cout<<std::setw(6)<< std::tan( numRad ) <<std::endl;
else
std::cout<< "infinitely" <<std::endl;
num=num+5;
}
To use constant M_PI
see How to use the PI constant in C++
To convert degrees to radians, use numRad = M_PI / 180.0
where M_PI should be a constant that holds the value od Pi. If you do not have such a constant defined in a header file, just define it yourself, like #define PI 3.14159265
The functions sin, cos and tan always require arguments in radians.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.