#include <iostream>
#include <stack>
#include <cstdio>
#include <cstring>
#include <cmath>
using namespace std;
bool isDigit(char c)
{
return (c <= '9' && c >= '0');
}
const char allOperator[] = "+-*/^^()";
bool isOperator(char c)
{
for (int j = 0; j < strlen(allOperator); ++j)
{
if (c == allOperator[j])
return 1;
}
return 0;
}
//expression verification
bool isLegal(const char* str)
{
int l = strlen(str);
for (int i = 0; i < l; ++i)
{
if ( !( isDigit(str[i]) || isOperator(str[i]) || str[i] == '.' ) )
return 0;
}
return 1;
}
int ofPosition(char c)
{
for (int i = 0; i < strlen(allOperator); ++i)
{
if (c == allOperator[i])
return i;
}
return -1;
}
//extract into double
double extractDigit(const char* s , int& len)
{
double value = 0;
int i = 0;
int point = 0;
while(isDigit(s[i]) || s[i] == '.')
{
++len;
if ( s[i] != '.' )
{
value = s[i] - '0' + value * 10;
}
else
{
++point;
}
}
for (int k = 0; k < point; ++k)
{
value *= 0.1;
}
return value;
}
//return 1 if a > b, need pop
bool priority(char a, char b)
{
if (a_pos == b_pos)
return 0;
if (b == '(') return 0;
int a_pos = ofPosition(a);
int b_pos = ofPosition(b);
if (a_pos > b_pos && abs(b_pos - a_pos) != 1 )
return 1;
return 0;
}
double compute(double a, double b, char v)
{
switch(v)
{
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
case '^':
return pow(a, b);
}
}
int main(int argc, char const *argv[])
{
input:
string expression;
cin >> expression;
// verify legal or not
if ( !( isLegal(expression.c_str() ) ) )
{
cout << "Format error. Please enter again.\n";
goto input;
}
stack<double> Operand;
stack<char> Operator;
for (int i = 0; i < expression.length(); ++i)
{
//Digit process
if (isDigit(expression[i]) )
{
int nextPos = 0;
Operand.push( extractDigit(&expression[i], nextPos) );
i += nextPos - 1;
}
//Operator verification
else if (isOperator(expression[i]) )
{
if (Operator.empty())
Operator.push(expression[i]);
else
{
while ( priority(Operator.top(), expression[i]) )
{
double num1 = Operand.top();
Operand.pop();
double num2 = Operand.top();
Operand.pop();
char sign = Operator.top();
Operator.pop();
Operand.push( compute(num1, num2, sign) );
}
Operator.push(expression[i]);
}
}
}
while (!Operator.empty())
{
double num1 = Operand.top();
Operand.pop();
double num2 = Operand.top();
Operand.pop();
char sign = Operator.top();
Operator.pop();
Operand.push( compute(num1, num2, sign) );
}
cout << Operand.top()<< endl;
return 0;
}
[Failed Practice]Suffix Expression
最新推荐文章于 2022-06-11 14:21:08 发布
