计算器....

#include<stdio.h>
#include<stack>
#include<string>
#include<iostream>
using namespace std;
stack<int> s;
stack<double> p;
stack<int> j;
char input[100];
int mat[8] = { 0,1,2,2,3,3,3,4 };
int out[8] = { 0,4,2,2,3,3,3,1 };
void getop(bool &judge, int &retn, int &i)
{
	if (i == 0 && s.empty() == true)
	{
		judge = true;
		retn = 0;
		return;
	}
	if (input[i] == 0)
	{
		judge = true;
		retn = 0;
		return;
	}
	if (input[i] >= '0'&&input[i] <= '9')
	{
		judge = false;
		retn = 0;
		for (; input[i] >= '0' && input[i] <= '9'; i++)
		{
			retn *= 10;
			retn += input[i] - '0';
		}
	}
	else
	{
		judge = true;
		if (input[i] == '+')
			retn = 2;
		if (input[i] == '-')
			retn = 3;
		if (input[i] == '*')
			retn = 4;
		if (input[i] == '/')
			retn = 5;
		if (input[i] == '(')
			retn = 7;
		if (input[i] == ')')
			retn = 1;
		if (input[i] == '%')
			retn = 6;
		i++;
		return;
	}
	if (input[i] == ' ')
		i++;
	return;
}
int judge()
{
	int i, jud = 0;
	int flag1 = 0, flag2 = 0;
	for (i = 0; input[i] != 0; i++)
	{
		if (input[i] >= '0'&&input[i] <= '9')
		{
			if (flag1 == 1 && flag2 == 1)
			{
				jud = 1; break;
			}
			flag1 = 1;
		}
		else if (input[i] == ' ')
			flag2 = 1;
		else
		{
			flag1 = 0; flag2 = 0;
		}
	}
	for (i = 0; input[i] != 0; i++)
	{
		if (input[i] == '(')
			j.push(i);
		if (input[i] == ')')
		{
			if (j.empty() == true)
			{
				jud = 2; break;
			}
			else
				j.pop();
		}
	}
	if (!j.empty())
		jud = 2;
	while (!j.empty())
		j.pop();
	return jud;
}
int main()
{
	while (gets_s(input))
	{
		int x = judge();
		if (x == 1)
			printf("两个数字之间缺省运算符\n"); 
		else if (x == 2)
			printf("缺省括号\n");
		else 
		{
			bool judge; int retn;
			int index = 0;
			while (!s.empty())
				s.pop();
			while (!p.empty())
				p.pop();
			while (true)
			{
				getop(judge, retn, index);
				if (judge == false)
					p.push((double)retn);
				else
				{
					double temp;
					if (s.empty() == true || mat[retn] > out[s.top()])
						s.push(retn);
					else
					{
						while (mat[retn] <= out[s.top()] && s.top() != 7 && s.top() != 0)
						{
							int cal_fu = s.top();
							s.pop();
							double a = p.top();
							p.pop();
							double b = p.top();
							p.pop();
							if (cal_fu == 2)
								temp = b + a;
							if (cal_fu == 3)
								temp = b - a;
							if (cal_fu == 4)
								temp = b * a;
							if (cal_fu == 5)
								temp = b / a;
							if (cal_fu == 6)
								temp = (int)b % (int)a;
							p.push(temp);
						}
						if (retn == 1)
							s.pop();
						else
							s.push(retn);
					}
				}
				if (s.size() == 2 && s.top() == 0)
					break;
			}
			printf("%.2f\n", p.top());
		}
	}
	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值