Visual Studio C++, Use beginner/intermediate level code, and switch such as “case”.
Write a program to be used as a calculator. It should be able to find addition (+), subtraction (-), multiplication (*), division (/), remainder of integer division (%), exponent(e), and squareroot (s) of numbers. The user enters inputs in the form: operator, number, (number): where the second number is not required for the exponent or squareroot . For example, if the user enters +5 4, then the program prints out 9: or if the user enters s 64, the program prints out 8. Test your program for a wide range of possible inputs including division by zero and squareroot of negative values.
Expert Answer
Solution:
#include<iostream>
#include<cmath>
using namespace std;
int main(){
char symbol;
int num1, num2;
float result;
int choice=0;
cout<<“Enter 1 if you want to do +, -, *, /, e, or % operation: “;
cin>>choice;
if(choice){
cout<<“nEnter your input in operator <number number format>: “; // Taking the input from user
cin>>symbol>>num1>>num2;
// cout<<symbol<<num1;
switch(symbol){
case ‘+’:{ //When the operator is +
result= num1+num2; // Adding the numbers
cout<<“nThe output is: “<<result;
break;
}
case ‘-‘:{ //When the operator is –
result= num1-num2; // Subtracting the numbers
cout<<“nThe output is: “<<result;
break;
}
case ‘*’:{ //When the operator is *
result= num1*num2; // Multiplying the numbers
cout<<“nThe output is: “<<result;
break;
}
case ‘/’:{ //When the operator is /
if(num2==0)
cout<<“n It is not possible to divid a number by 0”;
else{
result= num1/num2; // Dividing the numbers
cout<<“nThe output is: “<<result;
}
break;
}
case ‘%’:{ // When the operator is %
result= num1%num2;
cout<<“nThe output is: “<<result;
break;
}
case ‘e’: //When the operator is e
result= pow(num1, num2); // finding exponent of the numbers
cout<<“nThe output is: “<<result;
break;
}
}
else{
char ch;
cout<<“nEnter the operator and number in <operator number> format: “;
cin>>ch>>num1;
result= sqrt(num1); // Calculating square root of the number
cout<<“nThe output is: “<<result;
}
return 0;
}
Output: