HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Console calculator

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
consolecalculatorstackoverflow

Problem

I am a newbie programmer learning some C++. One of the exercises in my book asked me to write a basic console calculator that takes 2 numbers and an operation as input. I have done so and the program compiles (both with clang++ and g++) and runs fine.

I would like to know if:

  • I am making mistakes in my code that the compiler is allowing me to get away with



  • If my code can be made more resource efficient and/or shorter in length



#include 
using namespace std;
int main()
{
char operation;
double first_number;
double second_number;
double solution = 0;

cout > first_number;

cout > second_number;

cout > operation;
cin.ignore();

if (operation != '+' && operation != '-'&& operation != '/'&& operation != '*')
    {
        cout << "\nInvalid operation! Aborting!";
        cout << "\nPress Enter to exit.";
        cin.get();
        return 1;
    }//end if

if (operation == '+')
    {
        solution = first_number + second_number;
        cout << "\nYour answer is: " << solution << "\nPress Enter to exit.\n";
        cin.get();
        return 0;
    }//end if

if (operation == '-')
    {
        solution = first_number - second_number;
        cout << "\nYour answer is: " << solution << "\nPress Enter to exit.\n";
        cin.get();
        return 0;
    }//end if

if (operation == '*')
    {
        solution = first_number * second_number;
        cout << "\nYour answer is: " << solution << "\nPress Enter to exit.\n";
        cin.get();
        return 0;
    }//end if

if (operation == '/')
    {
        if ( second_number == 0 )
        {
            cout << "\nYou can't divide by zero! Aborting!";
            cout << "\nPress Enter to exit.";
            cin.get();
            return 2;
        }//end if
        solution = first_number / second_number;
        cout << "\nYour answer is: " << solution << "\nPress Enter to exit.\n";
        cin.get();
        return 0;
    }//end if

return 0;
}//end main

Solution

I'd try something like this. This is more robust as it checks for a 0 as the denominator and an invalid operation character.

Checking the former before attempting a calculation would be best, though you can still have it ask again for a proper denominator instead of just terminating the program right away. I did the latter here anyway for simplicity.

Checking the latter would involve either terminating the program right away or by throwing an exception since calculate() must return something (throw would replace return here, but should only be used in case of an error).

#include    // EXIT_FAILURE
#include 
#include  // std::logic_error

float calculate(const char operation, const float left, const float right)
{
    switch (operation)
    {
        case '+': return left + right;
        case '-': return left - right;
        case '*': return left * right;
        case '/': return left / right;
        default: throw std::logic_error("unsupported operator");
    }
}

int main()
{
    std::cout > left >> right;

    std::cout > operation;

    // terminate right away if dividing by zero
    if (operation == '/' && right == 0)
    {
        std::cerr << "Cannot divide by 0";
        return EXIT_FAILURE;
    }

    float result;

    // attempt the calculation (will throw if failed)
    try
    {
        result = calculate(operation, left, right);
    }
    // if it fails - catch exception, display it, then terminate
    catch (std::logic_error const& e)
    {
        std::cerr << "Error: " << e.what();
        return EXIT_FAILURE;
    }

    std::cout << "\nResult = " << result;
}

Code Snippets

#include <cstdlib>   // EXIT_FAILURE
#include <iostream>
#include <stdexcept> // std::logic_error

float calculate(const char operation, const float left, const float right)
{
    switch (operation)
    {
        case '+': return left + right;
        case '-': return left - right;
        case '*': return left * right;
        case '/': return left / right;
        default: throw std::logic_error("unsupported operator");
    }
}

int main()
{
    std::cout << "Enter your two numbers: \n\n";
    float left, right;
    std::cin >> left >> right;

    std::cout << "\nEnter your operation (+, -, *, /): ";
    char operation;
    std::cin >> operation;

    // terminate right away if dividing by zero
    if (operation == '/' && right == 0)
    {
        std::cerr << "Cannot divide by 0";
        return EXIT_FAILURE;
    }

    float result;

    // attempt the calculation (will throw if failed)
    try
    {
        result = calculate(operation, left, right);
    }
    // if it fails - catch exception, display it, then terminate
    catch (std::logic_error const& e)
    {
        std::cerr << "Error: " << e.what();
        return EXIT_FAILURE;
    }

    std::cout << "\nResult = " << result;
}

Context

StackExchange Code Review Q#13311, answer score: 8

Revisions (0)

No revisions yet.