四则运算器面对对象重构第一步

四则计算器面对对象重构第一步

#include <string>
#include <sstream>
using namespace std;
class CExpression
{
public:
	int RandomNumber(int low, int high);
	void SetnNumber(int data,int i)
	{
		data = RandomNumber(1, 4);
		number[i] = data;
	}
	void SetOperation(string data, int i)
	{
		data = RandomOperation();
		operation[i] = RandomOperation();
	}
	void SetExpression(string data)
	{
		data = GenerateExpression();
		expression = data;
	}
	string GetExpression(string data)
	{
		data = expression;
		return data;
	}
private:
	int number[4];
	string operation[3];
	string Polynomiail[2];
	string expression;
	double result;
	string RandomOperation();
	string GenerateExpression();
};
int CExpression::RandomNumber(int low, int high)  //生成[low,high]随机数 
{
	return (rand() % (high - low + 1) + low);
}

string CExpression::RandomOperation()     //生成四则运算符 
{
	string ope;
	switch (RandomNumber(1,4))
	{
	  case 1:ope = '+'; break;
	  case 2:ope = '-'; break;
	  case 3:ope = '*'; break;
	  case 4:ope = '/'; break;
	}
	return ope;
}


string CExpression::GenerateExpression()     //生成算式 
{
	stringstream ss;
	string str[2] = { "" };
	for (int i = 0; i < 2; i++)
	{
		int mode = RandomNumber(1, 3);
		if (mode == 1)
		{
			ss << '(' << number[2*i] << operation[i] << number[2*i+1] << ')';
		}
		if (mode == 2)
		{
			ss << number[2*i] << operation[i] << number[2*i + 1];
		}
		if (mode == 3)
		{
			if (number[i] != 0)
			{
				ss << number[2*i];
			}
		}
		str[i] = ss.str();
		ss.str("");
	}
	ss << str[0] << operation[2] << str[1];
	string exp = ss.str();
	ss.str("");
	return exp;
}
posted @ 2017-05-12 00:13  travail  阅读(178)  评论(1编辑  收藏  举报