【发布时间】:2013-01-12 14:07:43
【问题描述】:
我正在尝试评估一个作为字符数组的表达式并返回表达式的结果。
例如:
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。
【问题讨论】:
-
如果这是您的完整代码,而您“迷路”了,那么您需要首先考虑您要做什么,考虑算法和步骤,然后继续前进。你还有很多事情要做。
-
Soory,发布了错误的代码..请立即检查。
-
要求人们发现代码中的错误并不高效。您应该使用调试器(或添加打印语句)来隔离问题,然后构造一个minimal test-case。
-
您的堆栈将
double存储在struct node中;您将值从堆栈中弹出到int。这似乎是一个奇怪的安排。对于调试,要么使用调试器单步调试代码,要么添加足够多的打印语句以查看发生了什么。 -
首先做一个反向润色实现可能是一个很好的练习。 (例如,解析
1 2+3*)。这更容易做到。
标签: c string expression evaluation