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 <iostream>
#include <string>
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 < b; i++)
{
result *= a;
}
return result;
}
int main()
{
double a, b;
string function;
bool loop = 1;
while(loop)
{
system("CLS");
cin >> 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;
}
Command Pattern
. It will remove the need for a switch. \$\endgroup\$