在这里, 我采用了另外一种方式计算表达式:由于表达式是中序表达式,
首先,将表达式变为后序表达,然后利用逆波兰式的方法计算,仅仅只用一个数字栈即可。
但是该方法的缺点是:只能计算单个字符的运算,因为对于百位等数字计算,后序表达式数字有歧义。
// OOD.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include<iostream> // this is system header file, so use <>
#include<vector>
#include<stack>
#include<string>
using namespace std;
/*The expression is infix notation:
In order to develop a more readable code:
I change the problem into two part:
first, change the infix notation into Polish postfix notation (reverse Polish notation)
second, calculate the postfix notation*/
bool isnumber(char c)
{
if(c >= '0' && c <= '9')
return true;
else
return false;
}
int level(char c)
{
switch (c)
{
case '(':
return 0;
case '+':
return 1;
case '-':
return 1;
case '*':
return 2;
case '/':
return 2;
}
}
double cal(double n1,double n2, char sign)
{
switch (sign)
{
case '+':
return n1 + n2;
case '-':
return n1 - n2;
case '*':
return n1*n2;
case '/':
return n1/n2;
}
}
double CPE(string postfix)
{
double result = 0;
stack<double> numberstack;
for(int i = 0; i < postfix.size(); i++)
{
if(isnumber(postfix[i]))
{
int n1 = postfix[i] - '0';
numberstack.push(n1);
}
else
{
double n1 = numberstack.top();
numberstack.pop();
double n2 = numberstack.top();
numberstack.pop();
double n3 = cal(n2,n1,postfix[i]);
numberstack.push(n3);
}
}
return numberstack.top();
}
double calexpression(string s)
{
// first change the s from infix into postfix notation
stack<char> signstack;
string postfixstring = "";
int i = 0;
while(i < s.size())
{
char tmp = s[i];
if(isnumber(tmp))
{
while(i<s.size() && isnumber(tmp))
{
postfixstring += tmp;
i++;
tmp = s[i];
}
}
else
{
if(tmp == ')')
{
while(!signstack.empty() && signstack.top() != '(')
{
postfixstring += signstack.top();
signstack.pop();
}
signstack.pop();
}
else if (signstack.empty() || tmp == '(' || level(tmp) > level(signstack.top()))
signstack.push(tmp);
else if(level(tmp) <= level(signstack.top()))
{
while(!signstack.empty() && level(tmp) < level(signstack.top()))
{
if(signstack.top()!='(')
{
postfixstring += signstack.top();
signstack.pop();
}
}
signstack.push(tmp);
}
i++;
}
}
while(!signstack.empty())
{
postfixstring += signstack.top();
signstack.pop();
}
cout << "input expression is: " <<s<<endl;
cout << "postfix expression is: "<<postfixstring<<endl;
// calculate the postfix expression
double result = CPE(postfixstring);
cout << " the result for expression " << s << " is: "<< result << endl;
return result;
}
int main()
{
string s = "(1*(2-3)+1)/4";
double r = calexpression(s);
system("pause");
return 0;
}