评估后缀表达式时打印错误的值
Printing the wrong value when evaluating postfix expressions
我编写了一个用于计算后缀表达式的程序,我没有得到任何编译器 error/warnings 但我没有得到正确的输出,这可能意味着问题出在计算上,但我不知道不知道在哪里。
我的代码:
#include <ctype.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX 20
char s[MAX], top = 0;
void main() {
char postfix[MAX], ch;
int i, op1, op2, res;
clrscr();
printf("\n\t\t program to evaluate postfix expression");
printf("\n\t\t.......");
printf("\n enter the postfix expression:\n");
scanf("%s", &postfix);
for (i = 0; i < strlen(postfix); i++) {
ch = postfix[i];
if (isdigit(ch))
push(ch = '0');
else {
op2 = pop();
op1 = pop();
switch (ch) {
case '+':
res = op1 + op2;
break;
case '-':
res = op1 - op2;
break;
case '*':
res = op1 * op2;
break;
case '/':
res = op1 / op2;
break;
case '^':
res = pow(op1, op2);
break;
default:
printf("invalid choice");
}
push(res);
}
}
printf("result of above expression is:%d\n", pop());
getch();
}
push(int element) {
++top;
s[top] = element;
}
int pop() {
int element;
element = s[top];
--top;
return (element);
}
你应该更正错字并将push(ch = '0');
更改为
push(ch - '0');
ch
是一个字符,isdigit(ch)
,或者更好的是 isdigit((unsigned char)ch)
告诉你它是一个数字,ch
- '0'is the digit value, a number in the range
0to
9`.
您的代码 ch = '0'
将数字 '0'
存储到 ch
并压入此值,该值是您系统上的字符代码或 0
,ASCII 中的 48。
我编写了一个用于计算后缀表达式的程序,我没有得到任何编译器 error/warnings 但我没有得到正确的输出,这可能意味着问题出在计算上,但我不知道不知道在哪里。
我的代码:
#include <ctype.h>
#include <conio.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX 20
char s[MAX], top = 0;
void main() {
char postfix[MAX], ch;
int i, op1, op2, res;
clrscr();
printf("\n\t\t program to evaluate postfix expression");
printf("\n\t\t.......");
printf("\n enter the postfix expression:\n");
scanf("%s", &postfix);
for (i = 0; i < strlen(postfix); i++) {
ch = postfix[i];
if (isdigit(ch))
push(ch = '0');
else {
op2 = pop();
op1 = pop();
switch (ch) {
case '+':
res = op1 + op2;
break;
case '-':
res = op1 - op2;
break;
case '*':
res = op1 * op2;
break;
case '/':
res = op1 / op2;
break;
case '^':
res = pow(op1, op2);
break;
default:
printf("invalid choice");
}
push(res);
}
}
printf("result of above expression is:%d\n", pop());
getch();
}
push(int element) {
++top;
s[top] = element;
}
int pop() {
int element;
element = s[top];
--top;
return (element);
}
你应该更正错字并将push(ch = '0');
更改为
push(ch - '0');
ch
是一个字符,isdigit(ch)
,或者更好的是 isdigit((unsigned char)ch)
告诉你它是一个数字,ch
- '0'is the digit value, a number in the range
0to
9`.
您的代码 ch = '0'
将数字 '0'
存储到 ch
并压入此值,该值是您系统上的字符代码或 0
,ASCII 中的 48。