gpt4 book ai didi

c++ - 如何使用 ASCII 转换使用字符堆栈评估后缀表达式

转载 作者:行者123 更新时间:2023-11-28 04:42:41 24 4
gpt4 key购买 nike

代码是通过包含“stack.h”用户定义的头文件使用 ADT 实现的。

头文件中有栈操作的代码。由于不正确的 ASCII 转换,我得到的输出是奇怪的符号。

我应该对代码进行哪些更改才能获得正确的输出。

#include<iostream>
#include<string.h>
#include "stack.h"
using namespace std;

void posteva(char postfix[])
{
stack s;
int i=0;
while(postfix[i]!='\0')
{
char x=postfix[i];
if(isdigit(x))
{
s.push(x);
}
else
{
int op1=s.pop();
int op2=s.pop();
int res;
switch(x)
{
case '+':
res=op1+op2;
break;
case '-':
res=op1-op2;
break;
case '*':
res=op1*op2;
break;
case '/':
res=op1/op2;
break;
case '%':
res=op1%op2;
break;
case '^':
res=op1^op2;
break;
}
s.push(res);
}
i++;
}
cout<<"\n\nRESULT :"<<s.pop();
}

int main()
{
char postfix[20];
cout<<"\n\nEnter the postfix : ";
cin>>postfix;
posteva(postfix);
}

最佳答案

ASCII '2''3' 的值分别为 505150 + 51101,它恰好是 'e' 的 ASCII 值。

您添加的是 ASCII 编码值而不是数字。

要将数字转换为其等效的 int,请查看 ASCII table再次。当谈到数字时,你没有看到一些模式吗?尝试做例如'3' - '0' 看看你得到了什么。

当你得到它时,你就会有你的解决方案。

关于c++ - 如何使用 ASCII 转换使用字符堆栈评估后缀表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49899946/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com