7-4 表达式求值_1
在一个表达式中,只有“(”,“)”,“0-9”,“+”,“-”,“*”,“/”,“^”,请求出表达式的值。(“/”用整数除法)。
输入格式:
共1 行,为一个算式。 (算式长度<=30 其中所有数据在 0~2^31-1的范围内)。
输出格式:
共一行,为表达式的值。
输入样例:
在这里给出一组输入。例如:
1+(3+2)*(7^2+6*9)/(2)
结尾无空行
输出样例:
在这里给出相应的输出。例如:
258
结尾无空行
数据结构作业,非最优解,记录一下:
#include<iostream>
#include<stdlib.h>
#include<malloc.h>
#include<string.h>
#include<math.h>
#include<stdio.h>
#include<stack>
#define STACK_INIT_SIZE 105
#define STACKINCREMENT 2
#define ERROR 0
typedef char SElemType;
using namespace std;
static char priority[8]={8};
void priorityInit()
{
priority['#']=8;
priority['+']=5;
priority['-']=5;
priority['*']=4;
priority['/']=4;
priority['^']=3;
priority['(']=1;
priority[')']=1;
}
SElemType Precede(SElemType t1,SElemType t2)
{
SElemType f;
switch(t2)
{
case '+':if(t1=='('||t1=='=') f='<';
else f='>';
break;
case '-':if(t1=='('||t1=='=') f='<';
else f='>';
break;
case '*':if(t1=='*'||t1=='/'||t1==')'||t1=='^') f='>';
else f='<';
break;
case '/':if(t1=='*'||t1=='/'||t1==')'||t1=='^') f='>';
else f='<';
break;
case '^':if(t1==')'||t1=='^') f='>';
else f='<';
break;
case '(':if(t1==')')
{
printf("ERROR1\n");
exit(ERROR);
}
else f='<';
break;
case ')':switch(t1)
{
case '(':f='=';
break;
case '=':printf("ERROR2\n");
exit(ERROR);
default: f='>';
}
break;
case '=':switch(t1)
{
case '=':f='=';
break;
case '(':printf("ERROR2\n");
exit(ERROR);
default: f='>';
}
}
return f;
}
int Operate(int a,char o,int b)
{
switch(o)
{
case '+':
return a+b;
case '-':
return a-b;
case '*':
return a*b;
case '/':
return a/b;
case '^':
return pow(a,b);
default:
printf("ERROR!\n");
break;
}
}
int Calculate(stack<int> &N,stack<char> &O,char* a)
{
int len=strlen(a),i=0,temp=0,x=0,y=0;
char op;
a[len]='=';
O.push('=');
char ch=O.top();
while(ch!='='||a[i]!='=')
{
if(a[i]>='0'&&a[i]<='9')
{
temp=a[i]-'0';
i++;
while(a[i]>='0'&&a[i]<='9')
{
temp=temp*10+a[i]-'0';
i++;
}
N.push(temp);
}
else
{
switch(Precede(ch,a[i]))
{
case'<':O.push(a[i]); // 栈顶元素优先权低
i++;
break;
case'=':ch=O.top();O.pop(); // 脱括号并接收下一字符
i++;
break;
case'>':op=O.top();O.pop(); // 退栈并将运算结果入栈
y=N.top();
N.pop();
x=N.top();
N.pop();
N.push(Operate(x,op,y));
}
}
ch=O.top();
}
return N.top();
}
int main()
{
stack<int> Num;
stack<char> Op;
char ciallo[105];
scanf("%[^\n]",&ciallo);
cout<<Calculate(Num,Op,ciallo);
return 0;
}