码迷,mamicode.com
首页 > 其他好文 > 详细

四则运算的实现

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

标签:style   io   os   ar   sp   on   代码   c   amp   

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

代码如下:

#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;
}


四则运算的实现

标签:style   io   os   ar   sp   on   代码   c   amp   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!