计算表达式(前辍表达式变为后辍表达式之后,利用栈来做)

浮点数的,还有括号的存在;
#include<stdio.h>
#include<string.h>
#include<stack>
#include<stdlib.h>
#include <iostream>
using namespace std;

char a[1010];
char b[1010];
stack <char> s1;
stack <float> s2;

int i,j,n,m,t;
float x,y,z;

int fun(char x)
{
	switch(x)
	{
		case '+' :
		case '-' :return 1;
		case '*' :
		case '/' :return 2;
		case '(' :return 0;
		default  :return -1;
	}
}

float js(float x,float y,char z)
{
	switch(z)
	{
		case '+':return y+x;
		case '-':return y-x;
		case '*':return y*x;
		default :return y/x;
	}
}

int main()
{
	int p;
	char c[1010];
	float d;
	printf("请输入表达式的组数:");
        scanf("%d",&t);
	s1.push('#');
	while(t--)
	{
		j=0;
		printf("请输入这种形式的表达式: a+b= \n");
		scanf("%s",a);
		m=strlen(a)-1;

		for(i=0;i<m;i++)
		{
			if(a[i]>='0'&&a[i]<='9'||a[i]=='.') // 浮点数的处理
			{
			        memset(c,0,sizeof(c));
				p=0;
				while(a[i]>='0'&&a[i]<='9'||a[i]=='.')
				{
					b[j++]=a[i];
					c[p++]=a[i++];
				}
				d=atof(c);
				s2.push(d);
				i--;
			}

			else if(a[i]=='(')  
				s1.push(a[i]);

			else if(a[i]==')')
			{
				while(s1.top()!='(')
				{
					b[j++]=s1.top();
					x=s2.top();s2.pop();
					y=s2.top();s2.pop();
					x=js(x,y,b[j-1]);
					s2.push(x);
					s1.pop();
				}
				s1.pop();
			}

			else 
			{
				while(fun(s1.top())>=fun(a[i]))
				{
					b[j++]=s1.top();
					x=s2.top();s2.pop();
					y=s2.top();s2.pop();
					x=js(x,y,b[j-1]);
					s2.push(x);
					s1.pop();
				}
				s1.push(a[i]);
			}
		}

		while(s1.top()!='#')
		{
			b[j++]=s1.top();
			x=s2.top();s2.pop();
			y=s2.top();s2.pop();
			x=js(x,y,b[j-1]);
			s2.push(x);
			s1.pop();
		}
		b[j]='=';
		b[j+1]='\0';
		printf("后辍表达式为:");
		puts(b);
		cout << a;
		x=js(x,y,b[j-1]);
		printf("%f\n",s2.top());
		s2.pop();
	} 
	return 0;
}

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值