我的程序基本上采用一个表达式,最初是一个中缀表达式,将其转换为后缀,然后使用该后缀表达式来计算最终答案。我的程序不允许使用除数组之外的任何其他数据结构,所以我相信堆栈具有预定的大小。计算最终答案是有效的,前提是输入已经是后缀表达式:
Enter an expression: 5392-*+
Postfix expression is 5 3 9 2 - * +
The final answer is 26.
但是如果我输入中缀,我会得到什么:
Enter an expression: 5+3*(9-2)
Postfix expression is 5 3 9 2 - * +
The final answer is 3.
所以我意识到我需要我的“评估”函数来读取后缀表达式而不是中缀表达式,之前我的“infix_to_postfix”函数只是逐个打印出来的字符而不是将这些字符放入自己的数组中。 / p>
int main() {
int i, j, leftPar = 0, rightPar = 0, operand = 0, operator = 0;
char exp[20], operators[] = {'*', '/', '+', '-', '^'};
printf("Enter an expression: ");
scanf("%s", exp);
for (i = 0; i < sizeof(exp); i++) {
if (isalnum(exp[i]) == 1)
operand = operand + 1;
for (j = 0; j < 5; j++) {
if (exp[i] == operators[j])
operator = operator + 1;
}
if (exp[i] == '(')
leftPar = leftPar + 1;
if (exp[i] == ')')
rightPar = rightPar + 1;
}
if (operand > 7 && operand > 6){
printf("Too many operands and operators. The program will now close.\n");
return 0;
}
if (leftPar != rightPar) {
printf("Imbalanced parentheses. The program will now close.\n");
return 0;
}
printf("Postfix expression is ");
infix_to_postfix(exp);
printf("\n");
printf("The final answer is %d.\n", evaluate(exp));
}
char infix_to_postfix(char init[]) {
int x, y;
while (init[x] != '\0') {
if (isalnum(init[x]))
printf("%c ", init[x]); // Operand printed out immediately.
else if (init[x] == '(')
push(init[x]); // '(' character pushed.
else if (init[x] == ')') {
while ((y = pop()) != '(') // Popping elements from stack until reaching '('
printf("%c ", y);
}
else {
while (priority(init[x]) <= priority(stack[top])) // If expression operator has higher precedence than stack operator, expression operator is pushed onto stack. Else stack operator is popped and printed out.
printf("%c ", pop());
push(init[x]);
}
x++;
}
while(top != -1)
printf("%c ", pop()); // Remaining operators printed out.
return 0;
}
int evaluate(char init[]) {
int x, n1, n2, n3 = 0, num;
while(init[x] != '\0')
{
if(isdigit(init[x]))
{
num = init[x] - 48;
push(num);
}
else
{
n1 = pop();
n2 = pop();
switch(init[x])
{
case '+':
{
n3 = n1 + n2;
break;
}
case '-':
{
n3 = n2 - n1;
break;
}
case '*':
{
n3 = n1 * n2;
break;
}
case '/':
{
n3 = n2 / n1;
break;
}
}
push(n3);
}
x++;
}
return pop();
}
忽略第29行的“evaluate(exp)”,如何更改我的“infix_to_postfix”函数,甚至我的函数声明,以便它返回一个字符数组(或字符串,我不知道) “评估”功能可以作为参数吗?