王道机试3.1:栈的使用

//括号匹配
#include<stdio.h>
#include<stack>
using namespace std;
stack<int> s;
char str[110];
char ans[110];
int main(){
	while (scanf("%s",str)!=EOF)
	{
		int i;
		for ( i = 0; i < str[i]!=0; i++)
		{
			if (str[i]=='(')
			{
				s.push(i);
				ans[i] = ' ';
			}
			else if (str[i] == ')')
			{
				if (s.empty()==false)
				{
					s.pop();
					ans[i] = ' ';
				}
				else
				{
					ans[i] = '?';
				}
			}
			else
			{
				ans[i] = ' ';
			}
		}
		while (!s.empty())
		{
			ans[s.top()] = '$';
			s.pop();
		}
		ans[i] = 0;
		puts(str);
		puts(ans);
	}
	return 0;
}

在这里插入图片描述
代码实现:

//简易计算机
#include<stdio.h>
#include<stack>
using namespace std;
char str[200];
int mat[][5] = {
	1, 0, 0, 0, 0,
	1, 0, 0, 0, 0,
	1, 0, 0, 0, 0,
	1, 1, 1, 0, 0,
	1, 1, 1, 0, 0
};
stack<int> op;
stack<double> in;
void getOp(bool &reto, int &retn, int &i){
	if (i==0&&op.empty()==true)
	{
		reto = true;
		retn = 0;
		return;
	}
	if (str[i]==0)
	{
		reto = true;
		retn = 0;
		return;
	}
	if (str[i]>='0'&&str[i]<='9')
	{
		reto = false;
	}
	else
	{
		reto = true;
		if (str[i]=='+')
		{
			retn = 1;
		}
		else if (str[i]=='-')
		{
			retn = 2;
		}
		else if (str[i]=='*')
		{
			retn = 3;
		}
		else if (str[i] == '/')
		{
			retn = 4;
		}
		i += 2;
		return;
	}
	retn = 0;
	for (; str[i] != ' '&&str[i]!=0; i++)
	{
		retn *= 10;
		retn += str[i] - '0';
	}
	if (str[i]==' ')
	{
		i++;
	}
	return;
}
int main(){
	while (gets(str))
	{
		if (str[0]=='0'&&str[1]==0)
		{
			break;
		}
		bool retop;
		int retnum;
		int idx = 0;
		while (!op.empty())
		{
			op.pop();
		}
		while (!in.empty())
		{
			in.pop();
		}
		while (true)
		{
			getOp(retop, retnum, idx);
			if (retop==false)
			{
				in.push((double)retnum);
			}
			else
			{
				double tmp;
				if (op.empty()==true||mat[retnum][op.top()]==1)
				{
					op.push(retnum);
				}
				else{
					while (mat[retnum][op.top()] == 0){
						int ret = op.top();
						op.pop();
						int b = in.top();
						in.pop();
						int a = in.top();
						in.pop();
						if (ret==1)
						{
							tmp = a + b;
						}
						else if (ret==2)
						{
							tmp = a - b;
						}
						else if (ret == 3){
							tmp = a*b;
						}
						else
						{
							tmp = a / b;
						}
						in.push(tmp);
					}
					op.push(retnum);
				}
			}
			if (op.size()==2&&op.top()==0)
			{
				break;
			}
		}
		printf("%.2f\n", in.top());
	}
	return 0;
}

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值