Skip to content

Instantly share code, notes, and snippets.

@JackKell
Last active February 13, 2016 06:39
Show Gist options
  • Save JackKell/3362ed5c91d29f57c2d9 to your computer and use it in GitHub Desktop.
Save JackKell/3362ed5c91d29f57c2d9 to your computer and use it in GitHub Desktop.
// include statements
#include <iostream>
#include <math.h>
// using statements
using std::cout;
using std::endl;
// input char arrahandleExponent
char* expression = (char*)"(2+2*(3-6)-1)/2.5";
// function prototypes
float handleParenthesi();
// Handle exponents
float handleExponent(float currentValue = handleParenthesi()) {
if (*expression == '^') {
expression++;
return handleExponent(pow(currentValue, handleParenthesi()));
}
else {
return currentValue;
}
}
// Handle division and multiplication
float handleMultiplication(float currentValue = handleExponent()) {
if (*expression == '/' || *expression == '*') {
if (*(++expression - 1) == '/') {
return handleMultiplication(currentValue / handleExponent());
}
else {
return handleMultiplication(currentValue * handleExponent());
}
}
else {
return currentValue;
}
}
// Handle addition and subtraction
float handleAddition(float currentValue = handleMultiplication()) {
if (*expression == '-' || *expression == '+') {
if (*(++expression - 1) == '-') {
return handleAddition(currentValue - handleMultiplication());
}
else {
return handleAddition(currentValue + handleMultiplication());
}
}
else {
return currentValue;
}
}
// Handle parenthesis
float handleParenthesi() {
float result;
if (*expression == '(') {
expression++;
result = handleAddition();
expression++;
return result;
}
else {
return strtof(expression, &expression);
}
}
int main()
{
cout << handleAddition() << endl;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment