#include<iostream>
#include<cstdio>
#include<stack>
#include<math.h>
using namespace std;
int charToInt(char str[], int n)
{
int count = 0;
for (int i = n - 1; i >= 0; i--)
count += (str[i] - '0')*pow(10, n - 1 - i);
return count;
}
int Compare(stack<char>ope, char ch)//比较运算符的优先级
{
//判断当前优先级是否比栈顶操作符优先级高,操作符压入栈
char top_ope;
if (ope.empty())
top_ope = '&';
else
top_ope = ope.top();
if ((top_ope == '-' || top_ope == '+') && (ch == '*' || ch == '/'))
{
return 0;
}
else if (ope.empty() || ch == '(' || (top_ope == '(' && ch != ')'))
{
return 0;
}
//括号内的表达式计算完毕
else if (top_ope == '(' && ch == ')')
{
return 1;
}
//其他情况则计算
else
{
return -1;
}
}
int Calculate(char a[])
{
stack<int>num;
stack<char>ope;
int i = 0, j = 0, op_num, flag;
char temp[20];
while (a[i] != '\0')
{
if (a[i] >= '0'&&a[i] <= '9')
{
j = i + 1;
temp[0] = a[i];
while (a[j] >= '0'&&a[j] <= '9'&&a[j] != '\0')
{
temp[j - i] = a[j];
j++;
}
op_num = charToInt(temp, j - i);
//操作数入栈
num.push(op_num);
i = j;
}
while (1)
{
flag = Compare(ope, a[i]); //判断操作符优先级
if (flag == 0)
{
if (a[i] == '\0')//结束了避免i越界
{
i--;
break;
}
ope.push(a[i]); //压入操作符
break;
}
else if (flag == 1) //判断括号内的表达式是否结束
{
ope.pop();
i++;
}
else if (flag == -1) //进行数据处理
{
//取出数据栈中两个数据
float num_1 = num.top();
num.pop();
float num_2 = num.top();
num.pop();
float value = 0;
char ch = ope.top();
ope.pop();
if (ch == '+') //加法操作
{
value = num_1 + num_2;
}
else if (ch == '-') //减法操作
{
value = num_2 - num_1;
}
else if (ch == '*') //乘法操作
{
value = num_2 * num_1;
}
else if (ch == '/') //除法操作
{
value = num_2 / num_1;
}
num.push(value); //将得到的值压入数据栈
}
}
i++;
}
return num.top();
}
int main()
{
char a[20];
cout << "输入给定的表达式:\n";
cin >> a;
cout << Calculate(a) << endl;
getchar();
getchar();
return 0;
}
/*
(10+2)*6-12/3
*/