c - 这是用于评估后缀表达式的 C 代码。我添加了评论,看看我哪里出错了
问题描述
我制作了一个 C 程序来评估后缀表达式。输出错误。我在各个地方添加了打印消息,以查看我哪里出错了。出现在 for 循环体的第 4 或第 5 行。我不明白为什么会这样。
#include <stdio.h>
#include <string.h>
char exp[20];
int stck[15];
int tos = -1;
int isEmpty() {
if (tos == -1)
return 1;
return 0;
}
int isFull() {
if (tos == 9)
return 1;
return 0;
}
int pop() {
if (!(isEmpty()))
return stck[tos--];
else
printf("Underflow\n");
}
void push(int c) {
if (!(isFull()))
stck[++tos] = c;
else
printf("Overflow\n");
}
int isOperator(char c) {
if (c == '+' || c == '-' || c == '/' || c == '%' || c == '*')
return 1;
return 0;
}
main() {
int i, a, b, c;
printf("Enter the expression\n");
gets(exp);
for (i = 0; exp[i] != '\0'; i++) {
printf("Current symbol is %c\n", exp[i]);
if (!(isOperator(exp[i]))) {
push((int) exp[i]);
printf("Pushed %d into the stack\n", stck[tos]);
} else {
b = pop();
a = pop();
printf("Value of a and b are : %d and %d \n", a, b);
if (exp[i] == '+')
c = a + b;
if (exp[i] == '-')
c = a - b;
if (exp[i] == '*')
c = a * b;
if (exp[i] == '/')
c = a / b;
if (exp[i] == '%')
c = a % b;
push(c);
printf("C pushed. top of stack is now %d\n", stck[tos]);
}
}
printf("The value of expression is: %d\n", pop());
}
解决方案
Krati,评估的表达式是错误的,因为push((int)exp[i])
. 这会将 char 转换为其 ASCII 等价物,这是错误的。请将您的代码修改为 `push(exp[i] - '0') ,它将 char 转换为其等效数字。
例如'1' - 49(ASCII 值)。因此它将被评估为 49 - 48(ASCII of '0') = 1
注意:编写的代码不支持大于 9 的数字。您可以这样做。
- 将每个字符视为一个操作数,并在推送之前读取其值。表达式: ab*c+ (这里 a、b、c 是操作数。如果字符不是运算符,则将其视为操作数)您也可以使用以下数字 > 9 的实现
#include<stdio.h>
#include<string.h>
char exp[20];
int stck[15];
int tos=-1;
int isEmpty()
{
if(tos==-1)
return 1;
return 0;
}
int isFull()
{
if(tos==9)
return 1;
return 0;
}
int pop()
{
if(!(isEmpty()))
return stck[tos--];
else
printf("Underflow\n");
}
void push(int c)
{
if(!(isFull()))
stck[++tos]=c;
else
printf("Overflow\n");
}
int isOperator(char c)
{
if(c=='+' || c=='-' || c=='/' || c=='%' || c=='*' )
return 1;
return 0;
}
void main()
{
int i,a,b,c, operand;
printf("Enter the expression: ");
gets(exp);
for(i=0;exp[i]!='\0';i++)
{
//printf("Current symbol is %c\n",exp[i]);
if(!(isOperator(exp[i])))
{
printf("Enter '%c' value:", exp[i]);
scanf("%d", &operand);
push(operand);
printf("Pushed %d into the stack\n",stck[tos]);
}
else
{
b=pop();
a=pop();
printf("Value of a and b are : %d and %d \n",a,b);
if(exp[i]=='+')
c=a+b;
if(exp[i]=='-')
c=a-b;
if(exp[i]=='*')
c=a*b;
if(exp[i]=='/')
c=a/b;
if(exp[i]=='%')
c=a%b;
push(c);
printf("C pushed. top of stack is now %d\n",stck[tos]);
}
}
printf("The value of expression is: %d\n",pop());
getchar();
}
推荐阅读
- ios - 用户输入 11 位数字后关闭键盘
- node.js - 在 Node/express 静态文件中处理 CORS
- python - 为子图着色
- php - 如何在 Woocommerce 中删除更多负载并显示分页 WordPress
- javascript - 在 chart.js 条形图上限制标签
- android - 按钮按下一次,按钮保持增量值(连续)
- python - 未加载库:/usr/local/opt/mysql/lib/libmysqlclient.21.dylib 和未找到原因图像
- gremlin - 为什么 Gremlin JavaScript 使用“from_”映射而不是“from”?
- javascript - 如何在 html 中包含“包含”文件?
- design-patterns - 允许不同返回类型的设计模式