7.1 Cp 1918 问题 A: 简单计算器(栈的应用)

问题 A: 简单计算器

[命题人 : 外部导入]

时间限制 : 1.000 sec  内存限制 : 32 MB

解决: 1265提交: 2922统计

题目描述

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

输入

测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。

输出

对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。

样例输入 Copy

30 / 90 - 26 + 97 - 5 - 6 - 13 / 88 * 6 + 51 / 29 + 79 * 87 + 57 * 92
0

样例输出 Copy

12178.21

首先是传统方法,即将中缀转后缀后利用栈计算。

参考代码:

#include <iostream>
#include <string>
#include <stack>
#include <queue>
#include <map>
using namespace std;

struct node{
	double num; //操作数 
	char op; //操作符 
	bool flag; //true 表示操作数,false不是操作符 
};

string str;
stack<node> s; //操作符栈 
queue<node> q; //后缀表达式序列 
map<char,int> op;//建立操作符和优先级的映射 

void change() //将中缀表达式转换为后缀 
{
	node temp;
	for(int i=0;i<str.length();)
	{
		if(str[i]>='0'&&str[i]<='9')
		{
			temp.flag=true; //标记是数字数 
			temp.num=str[i++] -'0';
			while(i<str.length()&&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()
{
	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()); 
	}
	return 0;
}

可以利用输入技巧,利用空格区分数字和操作符,并将相应中间结果记录下来。

参考代码:

#include <iostream>
#include <cstring>
#include <iomanip>
using namespace std;
int main()
{
	double num[220];
	int i=0;
	double s,sum;
	char f;
	while(cin>>s) //第一个数 
	{
		memset(num,0,sizeof(num));
		num[0]=s; //将第一个数存入数组 
		f=getchar();
		if(f=='\n'||s==0)
		{
			break;
		}
		while(1)
		{
			cin>>f>>s; //每次都连续取一个操作符f和一个数字s 
			if(f=='*')
				num[i]*=s;//遇* /则*/s 
			else if(f=='/')
				num[i]/=s;
			else if(f=='+') //遇+则i自增,并在i处存入s 
				num[++i]=s; 
			else
				num[++i]=-s;// 遇-则i自增,并在i处存入-s
			if(getchar()=='\n')
				break;
		}
		sum=0;
		for(i;i>=0;--i) //将所有中间结果相加求和 
			sum+=num[i];
		cout <<fixed<<setprecision(2)<<sum<<endl;
	}
	return 0;
 } 

猜你喜欢

转载自blog.csdn.net/qq_43590614/article/details/105559074
cp
7.1