C++ program to build a trigonometric calculator
In this tutorial, we are going to make a Trigonometric Calculator using C++. Here, we will calculate basic trigonometric functions and their inverse and it can take input from users in degree as well as in radian.
Algorithm for creating the program
- We will take input as a whole string as “sin 90” and will give output
- We will create a user-defined function to take out ”90″ from the string.
- Then, we will give it as an argument to the pre-defined trigonometric function.
- We will use switch-case to compare the string to give output accordingly
C++ Code for trigonometric calculator
#include<iostream> #include<cmath> using namespace std; const float pie = 3.141; #define degree(x) (x*pie)/180 float input(int m,char ch[20]) { int i=3,j=0; char temp[10]; while(ch[i] !='\0') { if(ch[i]==' ') {i++; break;} i++; } while(ch[i]!='\0') { temp[j]=ch[i]; j++;i++; } if(m==1) return degree(atoi(temp)); else if(m==2) return atoi(temp); else return 0; } int main() { int m; char ch[20]; cout<<"*************** Welcome To Trignometric Calculater ***************"; cout<<"\nChoose the Input MODE:\n1) Degree\n2) Radian\n"; cin>>m; if(m<1&&m>2) { cout<<"Invalid Choice ! Choose again\n"; cin>>m; } cout<<"\nEnter the input as 'sin 90' and 'asin 0.5' for invrse and 'exit' to exit:\n"; while(1){ cout<<"\nInput: "; gets(ch); if(ch[0]=='e') exit(0); switch(ch[0]) { case 's': cout<<"Output: "<<sin(input(m,ch)); break; case 'c': cout<<"Output: "<<cos(input(m,ch)); break; case 't': cout<<"Output: "<<tan(input(m,ch)); break; case 'a': switch(ch[1]) { case 's': cout<<"Output: "<<sin(input(m,ch)); break; case 'c': cout<<"Output: "<<cos(input(m,ch)); break; case 't': cout<<"Output: "<<tan(input(m,ch)); break; }; break; default: cout<<"Invalid Input! Retry"; }; } return 0; }
Pre-defined function used to build a trigonometric calculator
- atio(): This function converts a string into an integer.
Output:
********** Welcome To Trignometric Calculater ********** Choose the Input MODE: 1) Degree 2) Radian 1 Enter the input as 'sin 90' and 'asin 0.5' for inverse and 'exit' to exit: Input: sin 90 Output: 1 Input: cos 60 Output: 0.5 Input: abc Invalid Input! Retry Input: exit
Leave a Reply