白日做梦嘞 2022-04-09 10:30 采纳率: 86.5%
浏览 13
已结题

栈的后缀表达式中不懂

问题遇到的现象和发生背景

#include <stdio.h>
#include <stdlib.h>
#include<string.h>
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define OK 1
#define max 100

typedef struct STACK
{
int date[max];
int top;
}stack;

stack* initStack()//创建线性存储结构的栈结构
{
stack* s;
s = (stack*)malloc(sizeof(stack));
s->top = -1;
return s;
}

void destroyStack(stack* s)//摧毁栈
{
free(s);
printf("清空成功!");
}

stack* clearStack(stack* s)//清空栈
{
s->top = -1;
printf("清理成功!");
return s;
}

int stackEmpty(stack* s)//判断链表是否为空
{
if (s->top >= max)
return FALSE;
if (s->top == -1)
return TRUE;
else
return FALSE;
}

int getTop(stack* s, int* e)//获取栈顶元素
{
if (s->top > -1 && s->top < max)
{
*e = s->date[s->top];
return OK;
}
else
return FALSE;
}

int push(stack* s, int e)//进栈操作
{
if (s->top == max - 1)
{
return ERROR;
}
s->top++;
s->date[s->top] = e;
return OK;
}

int pop(stack* s, int* e)//出栈操作
{
if (s->top == -1)
return ERROR;
*e = s->date[s->top];
s->top--;
return OK;
}

int stackLength(stack* s)//获取链表长度
{
return s->top++;
}

int main()
{
char str[100];
int i = 0, a, b, c, sum;
stack* s;
s = initStack();
gets_s(str);
while (str[i] != '\0')
{
if (str[i] >= '0' && str[i] <= '9')//1. 将字符串型的数字转换为整型(或者浮点型)。
{
sum = 0;
sum = str[i] - '0';
i++;
while (str[i] >= '0' && str[i] <= '9')
{
sum = sum * 10 + str[i] - '0';
printf("%d\n",sum);
i++;
}
push(s, sum);
}
if (str[i] == '+' || str[i] == '-' || str[i] == '' || str[i] == '/')//3. 遇到运算符(#),则将栈中的前两个数字(a和b)出栈,并将b#a的值压入栈中。
{
pop(s, &a);
pop(s, &b);
if (str[i] == '+')
push(s, b + a);
else if (str[i] == '-')
push(s, b - a);
else if (str[i] == '
')
push(s, b * a);
else if (str[i] == '/')
push(s, b / a);
else
printf("error\n");
}
i++;
}
pop(s, &c);//栈顶的数字出栈
printf("%s=%d\n", str, c);
return 0;
}

img


这是怎么变的 sum是整形 我不应该 用sum等于 str{i}-0 就行了吗 为什么sum*10还要加str

  • 写回答

1条回答 默认 最新

  • 对象被抛出 2022-04-09 10:33
    关注

    你得算上前面的结果啊, 比如12+3, 遍历到2的时候sum是1, 应该是1*10+2

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 12月1日
  • 已采纳回答 11月23日
  • 创建了问题 4月9日

悬赏问题

  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程