calculator using c++
Write a C++ program create a calculator for an arithmetic operator (+, -, *, /). The program
should take two operands from user and performs the operation on those two operands
depending upon the operator entered by user. Use a switch statement to select the operation.
Finally, display the result.
Some sample interaction with the program might look like this:
Enter first number, operator, second number: 10 / 3
Answer = 3.333333
Do another (y/n)? y
Enter first number, operator, second number: 12 + 100
Answer = 112
Do another (y/n)? n
#include<iostream>
using namespace std;
class calculator
{
private:
float n1,n2,result;
char op;
public:
void get();
void calculate();
};
void calculator::get()
{
cout<<"Enter 1st number"<<" "<<"operator"<<" "<<"Enter 2nd number:";
cin>>n1;
cin>>op;
cin>>n2;
}
void calculator::calculate()
{
switch(op)
{
case '+':
result=n1+n2;
cout<<"\nAnswer="<<result;
break;
case '*':
result=n1*n2;
cout<<"\nAnswer="<<result;
break;
case '/':
result=n1/n2;
cout<<"\nAnswer="<<result;
break;
case '-':
result=n1-n2;
cout<<"\nAnswer="<<result;
break;
}
}
int main()
{
char ch;
calculator obj;
x:obj.get();
obj.calculate();
cout<<"\nDo you want to continue(y/n)?\n";
cin>>ch;
if(ch=='y'||ch=='Y')
goto x;
return 0;
}
should take two operands from user and performs the operation on those two operands
depending upon the operator entered by user. Use a switch statement to select the operation.
Finally, display the result.
Some sample interaction with the program might look like this:
Enter first number, operator, second number: 10 / 3
Answer = 3.333333
Do another (y/n)? y
Enter first number, operator, second number: 12 + 100
Answer = 112
Do another (y/n)? n
#include<iostream>
using namespace std;
class calculator
{
private:
float n1,n2,result;
char op;
public:
void get();
void calculate();
};
void calculator::get()
{
cout<<"Enter 1st number"<<" "<<"operator"<<" "<<"Enter 2nd number:";
cin>>n1;
cin>>op;
cin>>n2;
}
void calculator::calculate()
{
switch(op)
{
case '+':
result=n1+n2;
cout<<"\nAnswer="<<result;
break;
case '*':
result=n1*n2;
cout<<"\nAnswer="<<result;
break;
case '/':
result=n1/n2;
cout<<"\nAnswer="<<result;
break;
case '-':
result=n1-n2;
cout<<"\nAnswer="<<result;
break;
}
}
int main()
{
char ch;
calculator obj;
x:obj.get();
obj.calculate();
cout<<"\nDo you want to continue(y/n)?\n";
cin>>ch;
if(ch=='y'||ch=='Y')
goto x;
return 0;
}
Comments
Post a Comment