#include <iostream>
#include<stack>
#include<ctype.h>
#include<string>
#include<cstdlib>
#include <algorithm>
using namespace std;
string SuffixtoIn();
void Calculator(const string&);
int main()
{
Calculator(SuffixtoIn());
system("pause");
}
//后缀转换成中缀
string SuffixtoIn()
{
cin>>noskipws;
stack<char> char_stack;
string str;
char c,e;
cout<<"请输入您要计算的公式(中缀表达式),以#为结尾:"<<endl;
cin>>c;
while('#'!=c)
{
while(isdigit(c))
{
str.push_back(c);
cin>>c;
if(!isdigit(c))
{
str.push_back(' ');
}
}
if(')'==c)
{
e=char_stack.top();
char_stack.pop();
while('('!=e)
{
str.push_back(e);
str.push_back(' ');
e=char_stack.top();
char_stack.pop();
}
}
else if('+'==c||'-'==c)
{
if(!char_stack.size())
char_stack.push(c);
else
{
do
{
e=char_stack.top();
char_stack.pop();
if('('==e)
char_stack.push(e);
else
{
str.push_back(e);
str.push_back(' ');
}
}while(char_stack.size()&&'('!=e);
char_stack.push(c);
}
}
else if('*'==c||'/'==c||'('==c)
{
char_stack.push(c);
}
if('#'==c)
break;
cin>>c;
}
while(char_stack.size())
{
e=char_stack.top();
char_stack.pop();
str.push_back(e);
str.push_back(' ');
}
return str;
}
//将中缀表达式进行计算
void Calculator(const string& str)
{
cout<<"后缀表示式为:"<<str<<endl;
stack<double> nums_stack;
double d,e;
int cur=0;
for(int i=0;i<str.size();i++)
{
if(' '==str[i])
continue;
string num_str;
while(isdigit(str[i]) || str[i]=='.')
{
num_str.push_back(str[i]);
if(str[i+1] == ' ')
{
d = stod(num_str);
nums_stack.push(d);
break;
}
i++;
}
switch(str[i])
{
case '+':
d=nums_stack.top();nums_stack.pop();
e=nums_stack.top();nums_stack.pop();
nums_stack.push(d+e);
break;
case '-':
d=nums_stack.top();nums_stack.pop();
e=nums_stack.top();nums_stack.pop();
nums_stack.push(d-e);
break;
case '*':
d=nums_stack.top();nums_stack.pop();
e=nums_stack.top();nums_stack.pop();
nums_stack.push(d*e);
break;
case '/':
d=nums_stack.top();nums_stack.pop();
e=nums_stack.top();nums_stack.pop();
nums_stack.push(d/e);
break;
}
}
d=nums_stack.top();nums_stack.pop();
cout<<"计算结果为:"<<d<<endl;
}
用栈实现简易计算器
最新推荐文章于 2023-09-24 08:56:53 发布