我正在尝试评估作为字符数组的表达式并返回表达式的结果。
例如:
char *myeExpression []= "(1+2) * 3"
应该返回结果 9。
这是我的代码:
struct node {
double element;
struct node *next;
} *head;
void push(int c); // function to push a node onto the stack
int pop(); // function to pop the top node of stack
void traceStack(); // function to //print the stack values
int prece(char j)
{
if(j=='*'||j=='/')
{
j=3;
}
else
{
if(j=='+'||j=='-')
{
j=2;
}
else
{
j=1;
}
}
return j;
}
int evaluate(char * a) {
int i = 0, j = 0,k,l,a1,b1; // indexes to keep track of current position
char *exp = (char *)malloc(sizeof(char)*100);
double res = 0;
char stack[5];
char tmp;
head = NULL;
// converting an infix to a postfix
for(i=0;i<10;i++)
{
a1=prece(a[i]);
b1=prece(stack[k]);
if(a1<=b1)
{
exp[l]=a[i];
l++;
}
else
{
stack[k]=a[i];
k++;
}
}
for(i=k;i>0;i--)
{
exp[l]=stack[i];
l++;
}
//end
i=0;
j=0;
k=0;
while( (tmp=exp[i++]) != '\0') { // repeat till the last null terminator
// if the char is operand, pust it into the stack
if(tmp >= '0' && tmp <= '9') {
int no = tmp - '0';
push(no);
continue;
}
if(tmp == '+') {
int no1 = pop();
int no2 = pop();
push(no1 + no2);
} else if (tmp == '-') {
int no1 = pop();
int no2 = pop();
push(no1 - no2);
} else if (tmp == '*') {
int no1 = pop();
int no2 = pop();
push(no1 * no2);
} else if (tmp == '/') {
int no1 = pop();
int no2 = pop();
push(no1 / no2);
}
}
return pop();
}
void push(int c) {
if(head == NULL) {
head = malloc(sizeof(struct node));
head->element = c;
head->next = NULL;
} else {
struct node *tNode;
tNode = malloc(sizeof(struct node));
tNode->element = c;
tNode->next = head;
head = tNode;
}
}
int pop() {
struct node *tNode;
tNode = head;
head = head->next;
return tNode->element;
}
中缀表达式评估发生但不完全。得到错误的结果,即 3 而不是 9。