Answer to Question #165737 in C++ for dave

Question #165737

Enter an operator (+, -, ×, /): +

Enter two operands: 5

8

5.0 + 8.0 = 13.0


1
Expert's answer
2021-02-22T16:06:05-0500
#include <iostream>
#include <iomanip>

int main()
{
    std::cout << "Enter an operator (+, -, *, /): "; 
    char operation;
    std::cin >> operation;

        if(!std::cin)
        {
            std::cout << "Bad input\n";
            return 1;
        }
    
    std::cout << "Enter two operands: "; 
    double operand1, operand2;
    std::cin >> operand1 >> operand2;

        if(!std::cin)
        {
            std::cout << "Bad input\n";
            return 1;
        }    

    double result;
    switch (operation)
    {
        case '+': result = operand1 + operand2; break;
        case '-': result = operand1 - operand2; break;
        case '*': result = operand1 * operand2; break;
        case '/': result = operand1 / operand2; break;
        default: std::cout << "Unexpected operator\n"; return 1;
    }

    std::cout << std::fixed<< std::setprecision(1)
              << operand1 << " " << operation << " "
              << operand2 << " = " << result << "\n";
    
    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