Write in C++ only Write a calculator program. The main menu will have the option
ID: 3683272 • Letter: W
Question
Write in C++ only
Write a calculator program. The main menu will have the option to exit, and several options for mathematical operators. The program will continually loop until specified to exit. The program must contain the operations of division, square root (or root in general), and one other of your choice. Square root can be performed by including the math.h library, and using the sqrt() function. The user will input all variables.
You must create 3 exception classes: one for handling the input stream fail state, one for divide by zero, and one for taking the square root of a negative number. Your program must check for the fail state every time the user enters something from the input stream. This is done by: if (!cin). If the input stream is in fail state throw the exception. You must also check if the user has tried to divide by zero, or root a negative number, and throw the appropriate exception.
Your program must have at least one try block (all of the throw calls should be in the try block). And it must have catch blocks for each of the three exceptions. Each block should report an appropriate message, and then allow the program to continue execution without exiting. The fail state catch block can resolve the issue with the following lines of code:
cin.clear();
cin.ignore(1024, ' ');
Explanation / Answer
#include <iostream>
#include <cmath>
#include <stdexcept>
using namespace std;
void main()
{
int i, c, n1,n1,r;
while(true)
{
cout<<"1. Division"<<endl;
cout<<"2. Sq. root"<<endl;
cout<<"3. Addition"<<endl;
cout<<"4. Exit"<<endl;
cout<<"Enter choice";
cin>>c;
switch (c)
{
case 1:
try
{
cout<<"Enter 2 numbers";
cin>>n1>>n2;
if(n2<0)
throw std::overflow_error("Divide by zero exception");
r=n1/n2;
cout<<"Division is "<<r;
}
catch(std::overflow_error e)
{
cout<<e.waht();
}
break;
case 2:
try
{
cout<<"Enter numbers";
cin>>n1;
if (n1 < 0 )
throw invalid_argument("sqrt received negative argument");
r=sqrt(n1);
cout<<"Sq. Root is "<<r;
}
catch(const exception& e)
{
cout << "Caught " << e.what() << endl;
}
break;
case 3:
cout<<"Enter 2 numbers";
cin>>n1>>n2;
r=n1+n2;
cout<<"Addition is "<<r;
break;
case 4:
return;
default:
cout<<"Pl. enter 1-4 only";
break;
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.