一个控制台下的数字表达式求值程序 (c/c++)
源代码见下:
#include <stdio.h>
#include <string>
#include <iostream>
#include <stdlib.h>
#include <vector>
#include <stack>
using namespace std;
//设置运算符优先级的算法
int Priority(const string opera) // 运算符优先级
{
if(opera=="+"||opera=="-")
{
return (1);
}
else if(opera=="*"||opera=="/")
{
return (2);
}
else
{
return (0);
}
}
void MiddlefixToPostfix(vector<string> &ivec1,vector<string> &ivec2)
//中缀表达式到后缀表达式的转换算法,ivec2中存放的是中缀表达式,将其转换为后缀表达式形式存放到ivec2中。
{
//定义一个存放操作符的栈对象。
stack<string> operatorstk;
for(vector<string>::size_type i=0;i!=ivec2.size();++i)
{
if(ivec2[i]=="(")
{
operatorstk.push(ivec2[i]);
}
else if(ivec2[i]=="+"||ivec2[i]=="-"||ivec2[i]=="*"||ivec2[i]=="/")
{
if(operatorstk.empty())
{
operatorstk.push(ivec2[i]);
}
else
{
if(Priority(ivec2[i])<=Priority(operatorstk.top()))
{
while( operatorstk.empty()==false && operatorstk.top()!="(" )
{
ivec1.push_back(operatorstk.top());
operatorstk.pop();
}
operatorstk.push(ivec2[i]);
}
else
{
operatorstk.push(ivec2[i]);
}
}
}
else if(ivec2[i]==")")
{
while(operatorstk.top()!="(")
{
ivec1.push_back(operatorstk.top());
operatorstk.pop();
}
operatorstk.pop();
}
else
{
ivec1.push_back(ivec2[i]);
}
}
while(operatorstk.empty()==false)
{
ivec1.push_back(operatorstk.top());
operatorstk.pop();
}
}
double GetPostfixExpressionValue(vector<string> &s)
//形参为存放后缀表达式
{
stack<double> operand; //定义一个栈对象operand用来存放后缀表达式的操作数
double vi,vc; //定义两个临时变量计算后缀表达式的操作数
// operand.push(34.54);
for(vector<string>::size_type i=0;i!=s.size();++i)
{
// if(operand.empty())
if(s[i]=="+")
{
vi=operand.top();
operand.pop();
vc=operand.top();
operand.pop();
operand.push(vi+vc);
}
else if(s[i]=="-")
{
vi=operand.top();
operand.pop();
vc=operand.top();
operand.pop();
operand.push(vc-vi);
}
else if(s[i]=="*")
{
vi=operand.top();
operand.pop();
vc=operand.top();
operand.pop();
operand.push(vi*vc);
}
else if(s[i]=="/")
{
vi=operand.top();
operand.pop();
vc=operand.top();
operand.pop();
operand.push(vc/vi);
}
else{
operand.push(atof(s[i].c_str())); //将容器对象s中第i个string转换为c风格字符串, 然后用atof函数将它转换为数字
//入栈。
}
}
return operand.top();
}
// const int MAX = 20;
int main()
{
vector<string> _ivec;
vector<string> ivec;
string str;
cout<<"请输入任意中缀形式的数字表达式(每个操作符和操作数,左括号和右括号之间用空格隔开
例如23 + 34 * ( 12 - 23 ) + 12 end,结尾处end表示结束输入): ";
while(cin>>str&&str!="end")
{
_ivec.push_back(str);
}
MiddlefixToPostfix(ivec,_ivec);
//后缀表达式
cout<<"后缀表达式为:";
for(vector<string>::size_type i=0;i!=ivec.size();++i)
{
cout<<ivec[i]<<" ";
}
cout<<endl;
cout<<"表达式所得结果为:";
double b;
b=GetPostfixExpressionValue(ivec);
cout<<b;
cout<<endl;
return 0;
}
上面文中代码经本人测试有点逻辑错误
错误发生在中缀到后缀转换算法上先修改如下