hdu 1237 简单计算器

#include<iostream>
#include<stdio.h>
#include<string.h>
#include<stack>
#include<iomanip>
using namespace std;
const int maxn = 201;
char s[maxn];
char lastexp[maxn];//后缀表达式串 
bool Operator(char a)
{
	if(a=='+'||a=='-'||a=='*'||a=='/')return true;
	return false;
}
bool check(char l,char r)//左运算(栈内)符优先级高 返回真 
{
	int a1,a2;//规律:左右运算符都是减或都是乘除的情况下 左边优先 
	if(l=='+'||l=='-')
	a1 = 2;
	if(l=='*'||l=='/')
	a1 = 4;
	if(r=='+'||r=='-')
	a2 = 1;
	if(r=='*'||r=='/')
	a2 = 3;
	if(l=='=')
	a1=0;
	if(a1>a2)return 1;
	else return 0;
}
int main()
{
	stack<char> op;
	stack<double> cul;
	while(cin.getline(s,201)&&(s[0]!='0'||s[1]!='\0'))
	{
		char *exp = lastexp;
		while(!op.empty())
			op.pop();
		while(!cul.empty())
			cul.pop();
		op.push('=');
		int n = strlen(s);
		s[n]=' ';
		n++;
		for(int i=0;i<n;i++)//将中缀表达式转化为后缀表达式 
		{
			if(Operator(s[i]))
			{
				char ch = op.top();
				while(check(ch,s[i]))//扫描到的运算符,与栈顶运算符优先级相比 
				{				//小于栈顶,栈顶运算符出栈并加入到后缀表达式中 
					*exp = ch; 		//重复这一过过程 ,直到高于栈顶运算符,
					exp++;			//并将此运算符加入到运算符栈中 
					op.pop();
					ch = op.top();
				}
				op.push(s[i]);
			}
			else
			{
				*exp = s[i];
				exp++;
			}
		}
		while(op.top()!='=')
		{
			*exp = op.top();
			op.pop();
			exp++;
		}
		*exp = '\0';
		//printf("%s\n",lastexp);
		n = strlen(lastexp);
		int num=0;
		for(int i=0;i<n;i++)//后缀表达式借助栈进行运算 
		{
			char ch = lastexp[i];
			
			if(ch>='0'&&ch<='9')//如果是数字,加入计算栈 
			{
				num = num*10+ (ch-'0');
				if(lastexp[i+1]==' ')
				{
					cul.push(num);
					num=0;
				}
			}
			else if(Operator(ch))//如果是运算符,取栈顶两元素 进行运算 
			{
				double a = cul.top();cul.pop();
				double b = cul.top();cul.pop();
				if(ch=='+')cul.push(b+a);
				else if(ch=='-')cul.push(b-a);
				else if(ch=='*')cul.push(b*a);
				else cul.push(b/a);
			}
		}
		double ans = cul.top();
	cout<<setprecision(2)<<setiosflags(ios::fixed)<<ans<<endl;
	}
} 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值