1.完整代码
#include <iostream>
#include <unordered_map>
#include <cstring>
#include <stack>
#include <stdio.h>
using namespace std;
/*定义全局栈*/
stack<double> num;//数据栈
stack<char> op;//运算符栈
void arithmetic()
{
auto first_num = num.top();//取出栈顶元素
num.pop();//更新栈顶元素
auto second_num = num.top();//取出第二个栈顶元素
num.pop();//更新栈顶
auto operation_symbol = op.top();//取出栈顶运算符
op.pop();
double sum = 0;
switch (operation_symbol)
{
case '+':
sum = second_num + first_num;
break;
case '-':
sum = second_num - first_num;
break;
case '*':
sum = second_num * first_num;
break;
case '/' :
sum = second_num / first_num;
break;
default:
break;
}
num.push(sum);
}
void Test()
{
//运算符容器。‘+’对应数字1,类似于ASCII码值的对应
unordered_map<char, int> Operator
{
{'+',1},{'-',1},{'*',2},{'/',2}
};
string str;
cout << "请输入表达式 (负数表示为:(0-a))" << endl;
cin >> str;
int flag = 1;//负数的处理
for (int i = 0; i < str.size(); i++)
{
auto c = str[i];
if (isdigit(c))
{
double data = 0;
int j = i;
while (j < str.size() && isdigit(str[j])&&str[j]!='.')
{
data = data * 10 + str[j++] - '0';//由于定义输入的是string类型,涉及到强制转换,数字字符减去‘0’,
//经过ASCII码值的转换就是对应的十进制数字
}
if (str[j] == '.')
{
j++;
int power = -1;
while (isdigit(str[j]))
{
data = data + (str[j] - '0') * pow(10,power);
j++;
power--;
}
}
i = j-1;//退出循环,说明j下标对应的不是数字了,退一位,是因为i在for循环要i++,无次-1操作就会出现,i的两次跳跃
num.push(data*flag);
flag = 1;
}
else if (c == '(')
{
op.push(c);
if (str[i + 1] == '-')
{
flag = -1;
i++;
}
else
flag = 1;
}
else if (c == ')')
{
while (op.top() != '(')//进入该循环是在处理括号内部的计算
{
arithmetic();
}
op.pop();
}
else//运算符压栈
{
if (c != '+' && c != '-' && c != '*' && c != '/')
{
cout << "非法输入!!!"<<endl;
return;
}
while (op.size() && op.top() != '(' && Operator[op.top()] >= Operator[c])
{
arithmetic();
}
op.push(c);
}
}
while (op.size())//只要还有运算符就说明没有结束运算
{
arithmetic();
}
cout <<"结果为:"<< num.top() << endl<<endl;
}
int main()
{
Test();
system("pause");
return 0;
}
2.测试结果
三、总结
1.四则运算处理乘除法和加减法的先后运算是一个比较棘手的点。借助unordered_map是一个很好的工具,当然也可以里面字符串和下标对应的方式,等等。但我认为unordered_map是比较方便的。
2.auto是一个可以自动识别(已经赋值的)变量的数据类型,为其分配内存空间不用额外声明是某种类型的变量。这个auto关键字有些编译器无法支持,这个也不要担心。本人用的是Microsoft Visual Studio 2019的编译器还是很强大的。
3.对负数的处理,可以采用在负号前面添加0的方式,当然最简单的还是把数字乘以 -1,这里采用flag来处理。