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

Calculator with simple input

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

Problem

This is "my" version of a basic C++ calculator, that requires a single line input (like 1+1) to calculate the result. I have been (self)learning the language for 2 months now. I don't pretend to have invented this code, but I haven't taken the time to search for this variation.

The functions included are:

-
Addition: 1 + 1 = 2

Input in program: 1+1

-
Subtraction: 1 - 1 = 0

Input in program: 1-1

-
Multiplication: 1 * 1 = 1

Input in program: 1*1

-
Division: 1 / 1 = 1

Input in program: 1/1

-
Exponentiation: 2 ^ 2 = 4

Input in program: 2^2

#include   
#include 

using namespace std;

class Math_Functions
{
private:
    double result;

public:
    double addition(double, double);
    double subtraction(double, double);
    double multiplication(double, double);
    double division(double, double);
    double exponentiation(double, double);
} math;

double Math_Functions::addition(double a, double b)
{
    result = a + b;
    return result;
}

double Math_Functions::subtraction(double a, double b)
{
    result = a - b;
    return result;
}

double Math_Functions::multiplication(double a, double b)
{
    result = a * b;
    return result;
}

double Math_Functions::division(double a, double b)
{
    result = a / b;
    return result;
}

double Math_Functions::exponentiation(double a, double b)
{
    result = 1;
    for (int i = 0; i > a;
        function = getchar();
        cin >> b;

        switch(function[0])
        {
            case '+' : cout << math.addition(a, b); break;
            case '-': cout << math.subtraction(a, b); break;
            case '*': cout << math.multiplication(a, b); break;
            case '/': cout << math.division(a, b); break;
            case '^': cout << math.exponentiation(a, b); break;
        }
        cout << endl << "Press Any Key to Continue . . . ";
        cin.sync();
        cin.ignore();
    }
    return 0;
}

Solution

If you're about to perform division, you must first check for 0 as the given divisor. To prevent this, it may be best to warn the user, and make sure they input a valid number before proceeding.

For the exponentiation, you can have a "shortcut" by returning 1 instantly if b is 0. There's no need to attempt calculations since anything raised to the 0 power is always 1. You should also handle negative powers in some way. The code will break if the user inputs such a value for b. This loop cannot handle all of these possible values.

Context

StackExchange Code Review Q#78031, answer score: 10

Revisions (0)

No revisions yet.