简易计算器

读入一个只包含+,-,*,/ 的非负整数计算表达式,计算该表达式的值





思路:给出一个中缀表达式然后转成后缀表达式,用一个栈来存操作符,队列存后缀表达式,最后计算后缀表达式。




#include<stdio.h>
#include<stdlib.h> 
#include<math.h>
#include<string.h>
#include<algorithm>
#include <vector> 
#include<stack> 
#include <queue>  
#include<map>
#include<iostream>  
#include <functional> 
#define MAX 1001
#define MAXD 6
#define TELNUM 10
using namespace std;

struct node{
	double num;
	char op;
	bool flag;
};

string str;
stack<node> s;
queue<node> q;
map<char,int> op;

void change()
{
	node temp;
	double num;
	for(int i = 0; i < str.size();)
	{
		if(str[i] >= '0' && str[i] <= '9')
		{
			temp.flag = true;
			temp.num = str[i++] - '0';
			while(i < str.size() && str[i] >= '0' && str[i] <= '9')
			{
				temp.num = temp.num * 10 + (str[i] - '0');
				i++;
			}
			q.push(temp);
		}
		else
		{
			temp.flag = false;
			while(!s.empty() && op[str[i]] <= op[s.top().op])/*当栈顶的操作符优先级大于当前操作符,就将栈中的操作符弹出到队列中,
									直到栈顶操作符优先级小于等于当前操作符,或者栈为空*/
			{
				q.push(s.top());
				s.pop();
			}
			temp.op = str[i];
			s.push(temp);
			i++;
		}
	}
	
	while(!s.empty())/*将剩余的操作符全部弹入到队列中*/
	{
		q.push(s.top());
		s.pop();
	}
}

double cal()
{
	double temp1,temp2;
	node cur,temp;
	while(!q.empty())
	{
		cur = q.front();/*指向队列头位置*/
		q.pop();
		if(cur.flag == true)
		{
			s.push(cur);/*是数字就压入栈中*/
		}
		else
		{
			temp2 = s.top().num;
			s.pop();
			temp1 = s.top().num;
			s.pop();
			
			temp.flag = true;
			if(cur.op == '+') temp.num = temp1 + temp2;
			else if(cur.op == '-') temp.num = temp1 - temp2;
			else if(cur.op == '*') temp.num = temp1 * temp2;
			else if(cur.op == '/') temp.num = temp1 / temp2;
			s.push(temp);/*把该次计算的值压入栈中*/
		}
		
	}
	return s.top().num;/*最后栈顶的元素就是后缀表达式的值*/
}


int main(void)
{
	op['+'] = op['-'] = 1;
	op['*'] = op['/'] = 2;
	
	while(getline(cin,str),str != "0")
	{
		
		for(string::iterator it = str.end(); it != str.begin(); it--)
		{
			if(*it == ' ')str.erase(it);
		}
		while(!s.empty())
		{
			s.pop();
		}
		change();
		printf("%.2f\n",cal());
	}
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值