#include<iostream>
#include<string>
#include<stack>
#include<iomanip>
#include<stdlib.h>
using namespace std;
int getFirst(char ch)
{
//获取优先级
if (ch == '(') return 1;
else if (ch == '+' || ch == '-') return 2;
else if (ch == '*' || ch == '/') return 3;
else return 4;
}
void calculate(stack<double> &mystack, char operation)
{
double n1, n2, n3;
n2 = mystack.top();
mystack.pop();
n1 = mystack.top();
mystack.pop();
if (operation == '+') {
n3 = n1 + n2;
}
else if (operation == '-') {
n3 = n1 - n2;
}
else if (operation == '*') {
n3 = n1 * n2;
}
else if (operation == '/') {
n3 = n1 / n2;
}
mystack.push(n3);
}
double calculator(string str)
{
//计算中缀表达式,默认输入是合法的
stack<double> mystack_number;
stack<char> mystack_operation;
int i = 0, j;
int size = str.size();//为字符串长度
char tmp_operation;
string tmp_num;
//开始遍历字符串
while (i < size) {
//如果为运算数
if (str[i] >= '0' && str[i] <= '9') {
j = i;
while ((j < size && str[j] >= '0' && str[j] <= '9')||(str[j] == '.' && j < size)) { j++; }
tmp_num = str.substr(i, j - i);//把运算符之前的内容存入临时字符串
mystack_number.push(atof(tmp_num.c_str()));//通过函数转化为对应浮点数
i = j;//将下一个要扫描的初始调整
}
//如果为非括号运算符
else if (str[i] == '+' || str[i] == '-' || str[i] == '*' || str[i] == '/') {
//运算符栈如果为空,则直接压入运算符
if (mystack_operation.empty()) {
mystack_operation.push(str[i]);
}
else {
while (!mystack_operation.empty()) {
tmp_operation = mystack_operation.top();
if (getFirst(tmp_operation) >= getFirst(str[i])) {
//计算
calculate(mystack_number, tmp_operation);
mystack_operation.pop();
}
else break;
}
mystack_operation.push(str[i]);
}
i++;
}
//如果为左括号
else {
if (str[i] == '(') mystack_operation.push(str[i]);
else {
//如果为右括号
while (mystack_operation.top() != '(') {
tmp_operation = mystack_operation.top();
//计算
calculate(mystack_number, tmp_operation);
mystack_operation.pop();
}
mystack_operation.pop();
}
i++;
}
}
//遍历完后,若栈非空,弹出所有元素
while (!mystack_operation.empty()) {
tmp_operation = mystack_operation.top();
//计算
calculate(mystack_number, tmp_operation);
mystack_operation.pop();
}
return mystack_number.top();
}
void printExpression(string &str)
{
char a,b[100]={0};
int i=0;
while(1)
{
cin>>a;
if(a!='#')
{
b[i]=a;
i++;
}
else
break;
}
str.assign(b);//把b存入str中
}
int main()
{
string str;
printExpression(str);//输入格式,表达式以#结尾
double num_res = calculator(str);
cout << fixed << setprecision(2);//保留两位小数
cout << num_res << endl;
return 0;
}
运行结果如下: