【发布时间】:2016-08-16 17:52:03
【问题描述】:
我的任务是实现 int isOperator(char *); 操作数被推送,操作符被置顶,弹出,表达式被推送。
Example:
6 5 2 3.14 + 8 * + 3 + *
Pushing: 6.000000
Pushing: 5.000000
Pushing: 2.000000
Pushing: 3.140000
Pushing: 2.000000+3.140000=5.140000
我的实现有问题吗? 这是我的 intOperator(char*)。
int isOperator(char *s){
int i;
char Ops[] = { '+', '-', '*', '/' };
for (i = 0; i < 4; i++)
{
if (s == Ops[i])
return (1);
return (0);
}
}
这是我推送和弹出操作数和运算符的实现。
S = CreateStack();
n = sizeof(postfixExpression) / sizeof(postfixExpression[0]); // Compute array size
for (i = 0; i<n; i++){ // Print elements of postfix expressions
printf("%s ", postfixExpression[i]);
}
printf("\n");
for (i = 0; i<n; i++){
if (isalnum(postfixExpression[i])){
Push(atof(postfixExpression[i]), S);
printf("Pushing: %d", atof(postfixExpression[i]));
}
else if (isOperator(postfixExpression[i]))
{
rightOperand = Top(S);
Pop(Top(S));
leftOperand = Top(S);
Pop(Top(S));
switch (isOperator(postfixExpression[i])){
case '+':
Push(leftOperand + rightOperand, S);
printf("Pushing: %d+%d=%d", leftOperand, rightOperand, leftOperand + rightOperand);
break;
case '-':
Push(leftOperand - rightOperand, S);
printf("Pushing: %d-%d=%d", leftOperand, rightOperand, leftOperand - rightOperand);
break;
case '*':
Push(leftOperand * rightOperand, S);
printf("Pushing: %d*%d=%d", leftOperand, rightOperand, leftOperand * rightOperand);
break;
case '/':
Push(leftOperand / rightOperand, S);
printf("Pushing: %d/%d=%d", leftOperand, rightOperand, leftOperand / rightOperand);
break;
default:
break;
}
}
else
break;
}
printf("%s\n", S);
DisposeStack(S);
return 0;
【问题讨论】:
-
isOperator函数应该会给你编译器警告。阅读它们。检查警告所在行的代码。尝试了解您收到警告的原因。 -
另外,试着按照函数中循环中的代码,它是做什么的?它会检查所有可能的运算符吗?
-
if (s == Ops[i])-->if (*s == Ops[i]),if (isalnum(postfixExpression[i])){-->if (isdigit(*postfixExpression[i])){ -
switch (isOperator(postfixExpression[i])){-->switch (*postfixExpression[i]){:isOperator(postfixExpression[i]) return 1 or 0
标签: c stack postfix-notation