计算器

#include "iostream"  
#include "stdio.h"  
#include "math.h"  
#include "vector"  
#include "stack"  
#include "queue"  
#include "memory.h"  
#include "algorithm"  
#include "string"  
using namespace std;  

char e[250],post[250];  
stack<char>Op;  

bool Isnum(char c)  
{  
	if(c>='0'&&c<='9')  
		return true;  
	return false;  
}  

int OPMode(char c)  
{  
	if(c=='+')      return 1;  
	if(c=='-')      return 2;  
	if(c=='*')      return 3;  
	if(c=='/')      return 4;  
	return -1;  
}  

/*1)如果遇到操作数,我们就直接将其输出。
	如果遇到操作符,则优先级根据将其放入到栈中
	从栈中弹出元素直到遇到发现更低优先级的元素(或者栈为空)为止。
	弹出完这些元素后,才将遇到的操作符压入到栈中。*/
void SplitExp(char* s)  //中缀表达式转换为后缀表达式
{  
	int i,j=0;  
	memset(post,'\0',sizeof(post));  
	for(i=0;i<strlen(s);i++)  
	{  
		if(s[i]==' ')  
			continue;  
		post[j++]=' '; 
		
		while(Isnum(s[i]))//数字直接弹出  
			post[j++]=s[i++];  
		int curop=OPMode(s[i]);  
		if(curop!=-1)  
		{  
			if(curop<=2)  //“+,-”号
				while(!Op.empty())//若不为空  
				{  
					post[j++]=Op.top(); //弹出,当前栈内只可能和加减号一个优先级的 
					Op.pop();  
				}  
			else  
			{  
				while(!Op.empty()&&OPMode(Op.top())>2) //若不为空,且栈顶为乘除号 
				{  
					post[j++]=Op.top();  
					Op.pop();  
				}  
			}  
			Op.push(s[i])   ;  //将当前符号压入堆栈
		}  
	}  
	while(!Op.empty()) //最后全部弹出赋值完毕 
	{  
		post[j++]=Op.top();  
		Op.pop();  
	}  
}  

stack<double>Num;  
double Cal()  //依次读取POST,首先把数字依次压入栈中,当读取到计算符的时候提取栈顶的两个数计算并将得到的数压入栈顶。
{  
	while(!Num.empty())  
		Num.pop();  
	int i=0,j;  
	int len=strlen(post);  
	while (i++<len)  
	{  
		if(post[i]==' ')  
			continue;  
		double cur=0;  
		bool hasnum=false;  
		while (Isnum(post[i]))  
		{	
			cur=post[i++]-'0';  
			hasnum=true;  
		}  
		if(hasnum)  
			Num.push(cur);  
		if(OPMode(post[i])!=-1)  
		{  
			double num1=Num.top();  
			Num.pop();  
			double num2=Num.top();  
			Num.pop();  
			switch(post[i])  
			{  
			case '+':       Num.push(num2+num1);break;  
			case '-':       Num.push(num2-num1);break;  
			case '*':       Num.push(num2*num1);break;  
			case '/':       Num.push(num2/num1);break;  
			}  
		}  
	}  
	return Num.top();  
}  

int main()  
{  
	while(gets(e))  
	{  
		if(strcmp(e,"0")==0)  
			break;  
		SplitExp(e);  
		printf("%.2f\n",Cal());  
	}  
} 


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值