标签:isp break bsp 结果 get for main pop char
源代码:http://www.cnblogs.com/jinggeer/p/6511788.html 来自博客园
更改后:实现括号运算 支持真分数
#include<stack>
#include<iostream>
#include<deque>
#include<string>
using namespace std;
bool isPra(char c)
{
if (c == ‘(‘ || c == ‘)‘)
return true;
else
return false;
}
int getPri(char c)
{
switch (c)
{
case ‘+‘:
case ‘-‘:
return 0;
break;
case ‘*‘:
case ‘/‘:
return 1;
break;
case ‘(‘:
case ‘)‘:
return -1;
break;
}
}
void check(char c, stack<char>& coll2, deque<char>& coll3)
{
if (coll2.empty())
{
coll2.push(c);
return;
}
if (isPra(c))
{
if (c == ‘(‘)
coll2.push(c);
else
{
while (coll2.top() != ‘(‘)
{
char ch = coll2.top();
coll3.push_back(ch);
coll2.pop();
}
coll2.pop();
}
}
else
{
char sym = coll2.top();
if (getPri(c) <= getPri(sym))
{
coll2.pop();
coll3.push_back(sym);
check(c, coll2, coll3);
}
else
{
coll2.push(c);
}
}
}
void allocate(deque<char>& coll1, stack<char>& coll2, deque<char>& coll3)
{
while (!coll1.empty())
{
char c = coll1.front();
coll1.pop_front();
if (c >= ‘0‘&&c <= ‘9‘)
{
coll3.push_back(c);
}
else
{
check(c, coll2, coll3);
}
}
while (!coll2.empty())
{
char c = coll2.top();
coll3.push_back(c);
coll2.pop();
}
}
void calculate(deque<char>& coll3, stack<int>& coll4)
{
while (!coll3.empty())
{
char c = coll3.front();
coll3.pop_front();
if (c >= ‘0‘&&c <= ‘9‘)
{
int op = c - ‘0‘;
coll4.push(op);
}
else
{
int op1 = coll4.top();
coll4.pop();
int op2 = coll4.top();
coll4.pop();
switch (c)
{
case ‘+‘:
coll4.push(op2 + op1);
break;
case ‘-‘:
coll4.push(op2 - op1);
break;
case ‘*‘:
coll4.push(op2*op1);
break;
case ‘/‘:
coll4.push(op2 / op1);
break;
}
}
}
}
int main()
{
deque<char> coll1;
stack<char> coll2;
deque<char> coll3;
stack<int>coll4;
string str;
cout << "请输入表达式,按enter结束:" << endl;
cin >> str;
for (int i = 0; i != str.size(); ++i)
{
coll1.push_back(str[i]);
}
allocate(coll1, coll2, coll3);
calculate(coll3, coll4);
cout << "计算结果为:" << coll4.top() << endl;
}
标签:isp break bsp 结果 get for main pop char
原文地址:http://www.cnblogs.com/yxsh/p/7608760.html