c++ Write a program named calculator.cpp that: • Prompts the user for two floati
ID: 3756502 • Letter: C
Question
c++
Write a program named calculator.cpp that: • Prompts the user for two floating point number operands and one math operator (+, -, *, /, ^) o Validate the user input for the math operators o Validate the user input for divide by 0 errors • Implements a function named calc() that determines the result of the mathematical operation o Return type: double o Parameter(s): double (operand1), char (operator), double (operand2) • Calls the calc() function to display the result of the operation in a well-formatted output • Prompts the user to decide whether to calculate another operation or not
The calc() function must NOT display any prompts, accept any user input, or display the result of the operation. Its purpose is simply to calculate the mathematical operation.
Explanation / Answer
#include<iostream>
#include<cmath>
using namespace std;
double calc(double operand1,double operand2,char o)
{
if(o=='+')
return operand1+operand2;
else if(o=='-')
return operand1-operand2;
else if(o=='*')
return operand1*operand2;
else if(o=='/')
{
if(operand2==0.0)
{
return -1;
}
else
return operand1/operand2;
}
else if(o=='^')
return pow(operand1,operand2);
else
return -2;
}
int main()
{
double operand1,operand2;
char o;
cout<<"Enter two floating point numbers :"<<endl;
cin>>operand1>>operand2;
cout<<"Enter one math operator (+, -, *, /, ^) :";
cin>>o;
if(calc(operand1,operand2,o)==-1)
cout<<"Division by 0 error!";
else if(calc(operand1,operand2,o)==-2)
cout<<"Invalid operation!";
else
cout<<"The value is :"<<calc(operand1,operand2,o);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.