算法:1、当输入操作数时,计算器便将其入栈
2、当显示操作符时,计算器将其用于栈顶的两个操作数,使操作数出栈,按照操作符的指示执行计算。
3、使步骤2的操作结果入栈。
4、读取下一个字符依次重复执行1 2 3 的步骤。当达到后缀表达式末尾时终止。
算法终止时,表达式的值位于栈顶。
用#作为不是同一个操作单元的分隔符(操作数,操作符)
本算法的前提要求: *字符串是语法正确的后缀表达式 *不存在一元操作符 *不存在求幂操作符
#include<iostream>
#include<stack>
#include<cmath>
#include<string>
using namespace std;
bool isIndent(char ch);
bool isOperand(char ch);
bool isDicim(char ch);
bool isOperator(char ch);
double computing(double n1,double n2,char ch);
double post_cal(const string &str);
int main()
{
cout<<"enter a right postfix expression :";
string st;
getline(cin,st);
cout<<"now begin computing !"<<endl;
cout<<"the result is "<<post_cal(st)<<endl;
return 0;
}
bool isIndent(char ch)
{
return ch==' ';
}
bool isOperand(char ch)
{
return (ch>='0'&&ch<='9');
}
bool isDicim(char ch)
{
return ch=='.';
}
bool isOperator(char ch)
{
return (ch=='+'||ch=='-'||ch=='/'||ch=='*');
}
double computing(double n1,double n2,char ch)
{
double result;
switch(ch)
{
case '+':result=n1+n2;break;
case '-':result=n1-n2;break;
case '/':result=n1/n2;break;
case '*':result=n1*n2;break;
}
return result;
}
double post_cal(const string &str)
{
stack<double> operands;
int index=str.size();
int i=0;
char ch=str[i];
double inte=0;
double dicim=0;
while(i<index)
{
if(!isIndent(ch))
{
if(isOperand(ch))
{
while(isOperand(ch))
{
inte=inte*10+(ch-'0');
i++;
ch=str[i];
}
if(isDicim(ch))
{
i++;
ch=str[i];
int s=0;
while(!isIndent(ch))
{
s++;
dicim=dicim+pow(0.1,i)*(ch-'0');
i++;
ch=str[i];
}
}
i--;
operands.push(inte+dicim);
}
else if(isOperator(ch))
{
double op1=operands.top();
operands.pop();
double op2=operands.top();
operands.pop();
operands.push(computing(op2,op1,ch));
cout<<op1<<" "<<op2<<endl;
}
}
inte=dicim=0;
i++;
ch=str[i];
}
return operands.top();
}