首页 > 其他 > 详细

四则运算的实现

时间:2014-09-21 23:01:12      阅读:365      评论:0      收藏:0      [点我收藏+]

闲来无事,写个四则运算的计算式【包括+,-,*,/,没有括号】;

代码如下:

#include <iostream>
#include <stack>
#include <string>
using namespace std;
class Calc
{
public:
	int judge (const string &str)
	{
		if (str.find ('=') == string::npos)
		{
			cout<<"input error"<<endl;
			return -1;
		}
	}
	int process (int a, int b, char op)
	{
		if (op == '+')
		{
			return a + b;
		}
		if (op == '-')
		{
			return a - b;
		}
		if (op == '*')
		{
			return a * b;
		}
		return a/b;
	}
	int result (const string &str)
	{
		string::const_iterator data = str.begin ();
		if (judge (str) == -1)
			return -1;
		while (*data != '=')
		{
			if (*data == '*')
			{
				numA = num.top ();
				num.pop ();
				data++;
				numB = *data - '0';
				num.push (process (numA, numB, '*'));
			}else if (*data == '/')
			{
				numA = num.top ();
				num.pop ();
				data++;
				numB = *data - '0';
				num.push (process (numA, numB, '/'));
			} else if (*data >= '0' && *data <= '9')
			{
				num.push (*data - '0');
			}else
			{
				op.push (*data);
			}
			data++;
		}
		while (!op.empty ())
		{
			numA = num.top ();
			num.pop ();
			numB = num.top ();
			num.pop ();
			num.push (process (numB, numA, op.top ()));
			op.pop ();
		}
		return num.top ();
	}


private:
	stack <int> num;
	stack <char> op;
	int numA;
	int numB;
};
int main ()
{
	string data;
	Calc calc;
	while (cin>>data)
	{

		cout<<calc.result (data)<<endl;
	}
	return 0;
}


四则运算的实现

原文:http://blog.csdn.net/u013316504/article/details/39457851

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!