利用C++的标准模板库(STL)中的栈(stack)实现一个计算器功能,该计算器模仿Windows系统自带的计算器,输入一串字符(可含括号),得出最终结果。
如,输入:
2+(3*1)=
输出:8
实现原理:先将输入的字符转化为后缀表达式,再计算该后缀表达式的值。
1 相关头文件
#include<stack>
#include<iostream>
#include<string>
using namespace std;2 将输入的字符转换为后缀表达式:
string inToPostfix()
{
stack<char>s;
char token;
string str;
cin >> token;
while (token != '=')
{
if (token >= 'a'&&token <= 'z')
cout << token << " ";
else
switch (token)
{
case ')':while (!s.empty() && s.top() !='(')
{
str.push_back(s.top());s.pop();
//cout << s.top() << " "; s.pop();
}
s.pop(); break;
case'(':s.push(token); break;
case'*':
case'/':while (!s.empty() && s.top() != '+'&&s.top() != '-'&&s.top() != '(')
{str.push_back(s.top()); s.pop();}
s.push(token); break;
case'+':
case'-':
while (!s.empty() && s.top() != '(')
{str.push_back(s.top()) ; s.pop();}
s.push(token); break;
default:s.push(token); break;
}
cin >> token;
}
while (!s.empty())
{
str.push_back(s.top());
s.pop();
}
str.push_back('=');
return str;
}3 计算该后缀表达式的值,最后输出即为结果
int evalPostFix(string token)
{
stack<int> s;
int a, b, result;
int i = 0;
while (token[i]!='=')
{
result = token[i] - '0';
if (result >= 0 && result <= 9)
s.push(result);
else
switch (token[i])
{
case '+':a = s.top(); s.pop(); b = s.top(); s.pop(); s.push(a + b); break;
case' - ':a = s.top(); s.pop(); b = s.top(); s.pop(); s.push(a - b); break;
case'*':a = s.top(); s.pop(); b = s.top(); s.pop(); s.push(a * b); break;
case'/':a = s.top(); s.pop(); b = s.top(); s.pop(); s.push(a / b); break;
case'^':a = s.top(); s.pop(); b = s.top(); s.pop(); s.push(a + b); break;
default:cout << "OOOOO\n";
}
++i;
}
return s.top();
}4 在main中实现
int main()
{
cout << evalPostFix(inToPostfix());
return 0;
}版权声明:本文为baidu_17313961原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。