简易计算器

 刚学了栈和队列,里面讲到栈的应用提到了这个,尝试写了一下

 这里只考虑了非常简单的情况:

1.输入一定合法

2.数据长度只有1并且都是整型

3.只考虑加减乘除,不考虑带括号的情况

总体思路是把输入全当成字符串,运用了一点算符优先法

#include<bits/stdc++.h>
using namespace std;
int op(char a)//根据符号的不同返回不同的优先级等级
{
	if (a == '+' || a == '-')
	{
		return 1;
	}
	else if (a == '*' || a == '/')
	{
		return 2;
	}
	else if (a == '#')
	{
		return 0;
	}
	
}
class shu {//保存数据的栈
	int top;
	int a[100];
public:
	shu()
	{
		top = -1;
	}
	~shu()
	{
	}
	int over()//如果只剩一个数据表明计算已经结束
	{
		if (top == 0)
			return 1;
		else
		{
			return 0;
		}
	}
	int gettop()
	{
		top--;
		return a[top + 1];

	}
	void pushtop(int b)
	{
		top++;
		a[top] = b;
	}
	friend void calculate(string a);

};
class fu {//保存操作符号的栈
	int top;
	char a[100];
public:
	fu()
	{
		top = 0;
		a[0] = '#';
	}
	~fu()
	{
	}
	int gettop()
	{
		top--;
		return a[top + 1];

	}
	void pushtop(char b)
	{
		top++;
		a[top] = b;
	}
	int compare(char b)//将栈顶元素和待用元素进行比较
	{
		if (op(a[top]) >= op(b))
		{
			return 1;
		}
		else
		{
			return 0;
		}
	}
	friend void calculate(string a);
};
void calculate(string a)
{
	fu ma;
	shu na;//生成两个栈
	int m = a.size();
	for (int i = 0; i <= m; i++)
	{
		if (i == m)//如果已经到了字符串末尾,就人为添加字符‘#’用于判断
		{
			char endd = '#';
			int x = na.gettop();
			int y = na.gettop();
			char z = ma.gettop();
			int c = 0;
			if (z == '+')
			{
				c = y + x;
			}
			else if (z == '-')
			{
				c = y - x;
			}
			else if (z == '*')
			{
				c = y * x;
			}
			else if (z == '/')
			{
				c = y / x;
			}
			na.pushtop(c);
			if (na.over() == 0)//如果数据栈还不止一个元素,说明没有结束
			{
				i--;
			}

		}
		else
		{
			if (a[i] == '+' || a[i] == '-' || a[i] == '*' || a[i] == '/')//判断读入字符是操作还是数据
			{
				if (ma.compare(a[i]))//如果前一个操作比后一个大,则可以计算前一个操作
				{
					int x = na.gettop();
					int y = na.gettop();
					char z = ma.gettop();
					int c;
					if (z == '+')
					{
						c = y + x;
					}
					else if (z == '-')
					{
						c = y - x;
					}
					else if (z == '*')
					{
						c = y * x;
					}
					else if (z == '/')
					{
						c = y / x;
					}
					na.pushtop(c);
					i--;
				}
				else//前一个操作比后一个小,把后来的操作压进操作栈
				{
					ma.pushtop(a[i]);
				}
			}
			else
			{
				na.pushtop(a[i] - '0');//把数据压入数据栈,因为他是字符,所以要减去0的码值
			}
		}
	}
	cout << na.gettop() << endl;//处理完后输出数据栈顶元素,即计算结果
}
int main()
{
	while (1)
	{
		string c;
		cin >> c;
		calculate(c);
	}

}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值