王道数据结构——表达式求值

33 篇文章 5 订阅

这里是很久以前写的代码

前转后

代码如下:

#include<stdio.h>
#include<string.h>
#include<stack>
using namespace std;
 
int main()
{
	char str[100];
	stack<char> s;
	while(~scanf("%s",str))
	{
		for(int i=0;i<strlen(str);i++)
		{
			if(str[i]=='+'||str[i]=='*')//如果符号为+或*压栈 
			{
				s.push(str[i]);
			}
			else if(str[i]==')')//遇到右括号时原样输出,并输出栈顶符号,栈顶符号出栈 
			{
				printf("%c",str[i]);
				printf("%c",s.top());
				s.pop();
			}
			else
			{
				printf("%c",str[i]);//其余字符原样输出 
			}
		}
	}
	return 0;
}

中缀表达式求值

代码如下:

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<ctype.h>
#include<stack>
using namespace std;
 
char str[1010];
char ans[1010][1010];
char *sep=" ";//分隔符 
char *p;
 
double cal(double a,double b,char c)
{
	if(c=='+') return a+b;
	if(c=='-') return a-b;
	if(c=='*') return a*b;
	if(c=='/') return a/b;
}
 
int judge(char p1,char p2)
{
	if(p1=='+'||p1=='-')
	{
		if(p2=='+'||p2=='-'||p2==')'||p2=='#') return 1;
		else return -1;
	}
	else if(p1=='*'||p1=='/')
	{
		if(p2=='(') return -1;
		else return 1;
	}
	else if(p1=='(')
	{
		if(p2==')') return 0;
		else return -1;
	}
	else if(p1==')') return 1;
	else if(p1=='#')
	{
		if(p2=='#') return 0;
		else return -1;
	}
}
 
int main()
{
	while(gets(str))
	{
		int len=strlen(str);
		str[len]=' ';
		str[len+1]='#';
		stack<char> s1;//符号栈
		stack<double> s2;//数字栈
		s1.push('#');
		p=strtok(str,sep);
		int l=0;
		memset(ans,0,sizeof(ans));
		do
		{
			strcpy(ans[l++],p);
		}while
		(
			p=strtok(NULL,sep)
		); 
		if(!strcmp(ans[0],"0")&&l==2) break;
		int index=0;
		while(ans[index][0]!='#'||s1.top()!='#')
		{
			if(!isdigit(ans[index][0]))//为运算符
			{
				char temp=s1.top();
				int tt=judge(temp,ans[index][0]);
				if(tt==-1)
				{
					s1.push(ans[index][0]);
					index++;
				}
				else if(tt==0)
				{
					s1.pop();
					index++;
				}
				else if(tt==1)
				{
					double a=s2.top();
					s2.pop();
					double b=s2.top();
					s2.pop();
					s2.push(cal(b,a,s1.top()));
					s1.pop();
				}
			}
			else//为运算符 
			{
				s2.push(atof(ans[index]));
				index++;
			}
		}
		printf("%.2lf\n",s2.top());
	}
	return 0;
}

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值