zoukankan      html  css  js  c++  java
  • 四则运算器面对对象重构第一步

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

    #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;
    }
    
  • 相关阅读:
    数据结构——自学笔记一
    Xmind软件——xmind 8 pro下载激活推荐!!
    Java学习笔记之面向对象、static关键字
    解决“var/log/sysstat/sa21: 没有那个文件或目录 请检查是否允许数据收集”
    c++.net学习笔记
    Android Studio学习-连接真机测试教学
    Servlet总结二(文件路径)
    Servlet总结一
    多线程的使用
    Lock
  • 原文地址:https://www.cnblogs.com/linshen/p/6843555.html
Copyright © 2011-2022 走看看