Answer to Question #183005 in C++ for Vincenzo Santoro

Question #183005

Write a program that mimics a calculator. The program should take as input:

  1. Two floating-point numbers
  2. The operation to be performed (+, -, /, *).

It should then output the numbers, the operator, and the result.

Additional notes:

  • Format your output to two decimal places.
  • For division, if the denominator is zero, output an appropriate message. The message should contain the word "error"

Some sample outputs follow:

3.5 + 4.0 = 7.50
13.973 * 5.65 = 78.95
1
Expert's answer
2021-04-24T18:53:49-0400
#include <iostream>
#include <iomanip>
using namespace std;


int main()
{
    float first_num, second_num;
    char operation;
    float result;
    
    cout<<"Enter the first number: ";
    cin>>first_num;
    
    cout<<"Enter the operation to be performed (+,-,/,or *): ";
    cin>>operation;
    
    cout<<"Enter the second number: ";
    cin>>second_num;
    
    switch(operation)
    {
        case '+':
            result=first_num+second_num;
            cout<<first_num<<operation<<second_num<<"="<<fixed<<setprecision(2)<<result;
            break;
        
        case '-':
            result=first_num - second_num;
            cout<<first_num<<operation<<second_num<<"="<<fixed<<setprecision(2)<<result;
            break;
            
        case '/':
            if (second_num==0)
            {
                cout<<"Error";
            }
            else
            {
                result=first_num/second_num;
                cout<<first_num<<operation<<second_num<<"="<<fixed<<setprecision(2)<<result;   
            }
            break;
            
        case '*':
            result=first_num * second_num;
            cout<<first_num<<operation<<second_num<<"="<<fixed<<setprecision(2)<<result;
            break;
        
        default:
            cout<<"Invalid Operation";
            break;
    }
    


    return 0;
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS