算术表达式帮忙纠错 在线等

来源:百度知道 编辑:UC知道 时间:2024/05/30 22:20:26
#include<iostream>
#include<cstring>
using namespace std;
int max(int x,char y);
char fu[101];
int shu[101];
int sum=0;
int top=0;
int tops=0;
int main()
{memset(fu,0,sizeof(fu));
memset(shu,0,sizeof(shu));
string str1;
char zf;
cin>>str1;
str1=str1+'@';
fu[top]='@';
int len=str1.length();
for(int i=0;i<len;i++)
{
zf=str1[i];
if((zf>='0')&&(zf<='9'))
sum=sum*10+int(zf-'0');
else { while(max(1,fu[top])>max(2,zf))
{shu[tops]=sum;tops++;sum=0;
if(fu[top]=='+') {tops=tops-2;shu[tops]=shu[tops]+shu[tops+1];top--;tops++;}
if(fu[top]=='-') {tops=tops-2;shu[tops]=shu[tops]-shu[tops+1];top--;tops++;}
if(fu[top]=='*') {tops=tops-2;shu[tops]=shu[tops]*shu[tops+1];top--;top

看了半天,才看懂一点点。
帮你改了下,测了几组数据都是对的。
不过我觉得应该还是有问题的。
你这个方法应该参照数据结构书上的算法,把
各个符号的优先级保存为矩阵,那样做起来更加直观明了。

其实对于算术表过式求值,我觉得最好还是用递归来做,
那样我觉得更加方便,稍微深一下,就可以处理小数了...

#include<iostream>
#include<string>
using namespace std;
int max(int x,char y);
char fu[101];
int shu[101];
int sum=0;
int top=0;
int tops=0;
int main()
{
memset(fu,0,sizeof(fu));
memset(shu,0,sizeof(shu));
string str1;
char zf;
cin>>str1;
str1=str1+'@';
fu[top]='@';
int len=str1.length();
for(int i=0;i<len;i++)
{
zf=str1[i];
if((zf>='0')&&(zf<='9'))
sum=sum*10+int(zf-'0');
else
{
if(max(1,fu[top])>max(2,zf))
{
shu[tops]=sum;
tops++;sum=0;
if(fu[top]=='+')
{tops=tops-2;shu[tops]=shu[tops]+shu