欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C#利用栈实现加减乘除运算

程序员文章站 2023-11-09 18:57:52
还是有一些小问题....懒得改了,但大体思路还是清晰的,首先定义一个运算符栈,一个数栈。 关于优先级,两个括号(,)优先级最低,其次是+、-,最高的是*、/ 关于运算法则,打个比方...

还是有一些小问题....懒得改了,但大体思路还是清晰的,首先定义一个运算符栈,一个数栈。

关于优先级,两个括号(,)优先级最低,其次是+、-,最高的是*、/

关于运算法则,打个比方,"(3+5*4)+3"这个串

首先遇到左括号,直接压入运算符栈,然后是3,直接压入数栈,然后遇到5,压入数栈,遇到*,将其压入运算符栈,遇到右括号,将运算符栈顶的*取出,取出两个数栈栈顶的数,进行乘法运算,将运算结果压入数栈,因为此时运算符栈顶仍不是左括号,取出栈顶的+号,拿出数栈栈顶的两个数,进行加法运算,并将结果压入数栈。此时栈顶是左括号了,那么将左括号弹出栈。此时数栈里还有一个23,运算符栈为空。接着来。此时轮到了+号,直接压入数栈,遇到3,直接压入数栈。此时发现串已经结尾了,但是运算符栈还没有清空。那么就清空吧,把+号拿出来,数栈的23和3拿出来,加法运算,结果压入数栈。此时运算符栈清空,数栈剩个26。这就是最后的结果。是不是很简单但是有一点云里雾里。。

说一下运算规则吧。优先级大家都知道了,优先级从高到低依次是 "*/","+-","()",每当要压运算符时,首先得看看运算符栈里有什么,如果没有,肯定是可以直接压入的,左括号也是可以不管三七二十一直接压入的,除此之外,如果遇到栈顶运算符优先级更高时,是必须将栈顶运算符先取出来运算,直到栈顶元素优先级小于或者等于要压入的运算符的优先级才可压入。比如3*5+5+5,在压入第一个+号时,必须先将栈里的*号先拿出来运算结束后,才能放进去,否则计算结果将是错误的。当压入的是右括号时,必须一直弹运算符栈进行运算,直到遇到左括号为止。当串扫描到末尾时,也必须将运算符栈清空,最后留在数栈的数就是结果。关于小数点,关于复数加减运算,我写的小程序里有了一定的处理

C#利用栈实现加减乘除运算

就类似于这样的简单功能。。。。恩,将就看看吧。。程序不完善,不过也懒得改了,毕竟是练习,最近事又多。

下面贴一下源码

主要用到的几个类和方法:

   类parser   的parse方法,比如给一个“3+4i”的字符串,返回给你一个3个结点的队,队列第一个元素是一个complexnumber对象,实数域为3,队列的第二个元素是“+”号,队列第三个元素是一个complexnumber对象,实数域为0,虚数域为4。

    类operators    用于测试字符是否是运算符,用来进行控制运算,比较运算符优先级....

    类handler   给一个字符串,他帮你处理,返回给你一个结果。其实就是调一下parser类的方法去解析一下字符串,然后算一下结果,然后返回结果。

 类complexnumber,就是复数类啊,不用说了,提供实数域虚数域,getset方法,加减乘除以及tostring()方法

using system;
using system.collections;
using system.text;
namespace myspace{
	class parser{
		public static queue parse(string input){
			char[] arr = input.tochararray();
			queue queue = new queue();
			foreach(char x in arr){
				queue.enqueue(x);
			}
			queue = parsestringqueue(queue);
			return queue;
		}
		
		//传入字符串队列,返回封装好的队列。
		//complexnumber对象或char类型运算符各占用一个结点
		private static queue parsestringqueue(queue queue){
			queue secondq = new queue();
			char c;
			stringbuilder sb = null;
			string temp;
			int count = queue.count;
			bool flag = false; //false表示允许创建新sb对象进行缓存数字字符串
			for(int i=0;i<count;i++){
				c = (char)queue.dequeue();
				
				if(!operators.contains(c)){
					//如果扫描到的不是运算符,则将其加入到buffer尾部
					if(!flag){
						flag = true;
						sb = new stringbuilder();
					}
					sb.append(c);
				}
				if(operators.contains(c) || queue.count == 0){
					//如果扫描到的是运算符,则将缓冲区中的串加入队尾
					if(sb != null && flag == true){
						temp = sb.tostring();
						try{
							if(temp.endswith("i")){
									if(temp.length==1){
										secondq.enqueue(new complexnumber(0,1));
									}else{
									//i前有数字则开出数字部分。
										temp = temp.substring(0,temp.length-1);
										secondq.enqueue(new complexnumber(0,double.parse(temp)));
									}
								
							}else{
								secondq.enqueue(new complexnumber(double.parse(temp),0));
							}
							sb = null;
							flag = false;
						}catch(exception e){
							console.writeline("error");
						}
					}
					//如果是运算符,则最后将运算符放入队。
					if(operators.contains(c)){
						secondq.enqueue(c);
					}
				}
			}
			
			return secondq;
		}
	}
	class complexnumber{
		private double m_drealpart;
		private double m_dimaginpart;
		public complexnumber(){
			m_drealpart = 0.0;
			m_dimaginpart = 0.0;
		}
		public complexnumber(double r,double i){
			m_drealpart = r;
			m_dimaginpart = i;
		}
		public complexnumber(complexnumber c){
			m_drealpart = c.getrealpart();
			m_dimaginpart = c.getimaginarypart();
		}
		//get,set方法
		public double getrealpart(){
			return m_drealpart;
		}
		public double getimaginarypart(){
		    return m_dimaginpart;
		}
		public void setrealpart(double d){
		    m_drealpart = d;
		}
		public void setimaginarypart(double d){
		    m_dimaginpart = d;
		}
		public complexnumber complexadd(complexnumber c){
		    return new complexnumber(this.m_drealpart + c.getrealpart(),this.m_dimaginpart + c.getimaginarypart());
		}
		public complexnumber complexadd(double c){
			return new complexnumber(
		    this.m_drealpart + c, 
			this.m_dimaginpart);
		}
		
		public complexnumber complexminus(complexnumber c){
		   return new complexnumber(this.m_drealpart - c.getrealpart(),this.m_dimaginpart - c.getimaginarypart());
		}
		public complexnumber complexminus(double c){
			return new complexnumber(this.m_drealpart - c, this.m_dimaginpart);
		}
		//乘
		public complexnumber complexmulti(complexnumber c){
			return new complexnumber(
			this.m_drealpart * c.getrealpart() 
			- this.m_dimaginpart * c.getimaginarypart(),
			this.m_drealpart * 
			c.getimaginarypart()
			+ this.m_dimaginpart * 
			c.getrealpart());
		}
		public complexnumber complexmulti(double c){
			return 
				new complexnumber(
					this.m_drealpart * c,
					this.m_dimaginpart * c);	
		}
		//除
		public complexnumber complexdivision(complexnumber c){
			return 
				new complexnumber((this.m_drealpart*c.getrealpart()
				+this.m_dimaginpart*c.getimaginarypart())/(c.getrealpart()*c.getrealpart()+c.getimaginarypart()*c.getimaginarypart())
				,(this.m_dimaginpart*c.getrealpart()-this.m_drealpart*c.getimaginarypart())
				/(c.getrealpart()*c.getrealpart()+c.getimaginarypart()*c.getimaginarypart())); 
		}
		public complexnumber complexdivision(double c){
			return new 
				complexnumber(this.m_drealpart/c,this.m_dimaginpart/c);
		}
	
		public override string tostring(){
		   return "(" + m_drealpart + " + " + m_dimaginpart + " i" + ")";
		}
	}
	class operators{
		static char[][] signoperator;
		
		static operators(){
			signoperator = new char[3][];
			signoperator[0] = new char[2];
			signoperator[0][0]='*';
			signoperator[0][1]='/';
			signoperator[1] = new char[2];
			signoperator[1][0]='+';
			signoperator[1][1]='-';
			signoperator[2] = new char[2];
			signoperator[2][0]='(';
			signoperator[2][1]=')';
		}
		
		public static int comparepriority(char firstsign,char secondsign){
			int priorityf = 0,prioritys = 0;
			for(int i = 0; i<signoperator.length;i++){
				foreach(char x in signoperator[i]){
					if(firstsign == x){
						priorityf = i;
					}
					if(secondsign == x){
						prioritys = i;
					}
				}
			}
			
			return (priorityf-prioritys);
		}
		
		public static bool contains(char x){
			foreach(char[] arr in signoperator){
				foreach(char y in arr){
					if(x == y){
						return true;
					}
				}
			}
			return false;
		}
		
		public static complexnumber compute(char ope,complexnumber c1,complexnumber c2){
			complexnumber result = null;
			switch(ope){
				case '+':result=c1.complexadd(c2);break;
				case '-':result=c2.complexminus(c1);break;
				case '*':result=c1.complexmulti(c2);break;
				case '/':result=c1.complexdivision(c2);break;
			}
			return result;
		}
	}
	
	class handler{
		private stack complexnumberstack = new stack();
		private stack operatorstack = new stack();
		private static handler handler = new handler();
		private handler(){}
		public static handler gethandler(){
			return handler;
		}
	
		public complexnumber process(string inputstring){
			queue queue = parser.parse(inputstring);
			complexnumber complexnumber = null;
			char c,top,ct;
			int count = queue.count;
			for(int i=0;i<count;i++){
				object obj = queue.dequeue();
				if(obj is char){
					c = (char)obj;
					if(operatorstack.count == 0){
						operatorstack.push(c);
					}else{
						top = (char)operatorstack.peek();
						if(c=='('){
							operatorstack.push(c);  //左括号直接压入。不判断栈顶
						}else if(c==')'){	
						//右括号压入前观察栈顶,若栈顶是左括号,则弹出栈顶的左括号
						//否则弹出栈顶运算符,从数栈中弹出操作数进行运算,并将结果重新压入数栈,直到遇到左括号
							while((ct=(char)operatorstack.pop())!='('){
								complexnumber c1 = (complexnumber)complexnumberstack.pop();
								complexnumber c2 = (complexnumber)complexnumberstack.pop();
								complexnumber c3 = operators.compute(ct,c1,c2);
								complexnumberstack.push(c3);
							}
						}else if(operators.comparepriority(top,c)<0){
							//若即将压入的运算符不是括号,则比较栈顶运算符和即将压入的运算符的优先级
							//如果栈顶优先级高,则将栈顶运算符取出运算,直到栈顶优先级不大于其。
							while(operators.comparepriority((char)operatorstack.peek(),c)<0){
								complexnumber c1 = (complexnumber)complexnumberstack.pop();
								complexnumber c2 = (complexnumber)complexnumberstack.pop();
								complexnumber c3 = operators.compute((char)operatorstack.pop(),c1,c2);
								complexnumberstack.push(c3);
								operatorstack.push(c);
							}


						}else{
							operatorstack.push(c);
						}
					}
				}else if(obj is complexnumber) {
					complexnumber = (complexnumber)obj;
					complexnumberstack.push(complexnumber);
				}
				
				if(queue.count == 0){
					if(operatorstack.count != 0){
						while(operatorstack.count != 0){								
							c = (char)operatorstack.pop();
							complexnumber c1 = (complexnumber)complexnumberstack.pop();
							complexnumber c2 = (complexnumber)complexnumberstack.pop();
							complexnumber c3 = operators.compute(c,c1,c2);
							complexnumberstack.push(c3);
						}
					}
				}
			}
			
			return (complexnumber)complexnumberstack.pop();
		}
	}
	class primeclass{
		static void main(string[] args){
			string input;
			handler handler = handler.gethandler();
			while(!(input = console.readline()).equals("end")){
				complexnumber c = (complexnumber)handler.process(input);
				console.writeline(c);
			};
		}
	}
	
}

don_yao整合修复一些bug后的代码

using system;
using system.collections;
using system.collections.generic;
using system.text;

// 解析计算字符串公式
namespace calcustrformula
{
  // 处理类
  class handler
  {
    private stack _complexnumberstack = new stack();
    private stack _operatorstack = new stack();
    private parser _parser = new parser();
    private operators _operators = new operators();

    private static handler _instance;
    public static handler instance
    {
      get
      {
        if (_instance == null)
        {
          _instance = new handler();
        }
        return _instance;
      }
    }

    public complexnumber process(string inputstring)
    {
      _complexnumberstack.clear();
      _operatorstack.clear();

      queue<object> queue = _parser.parse(inputstring);
      complexnumber complexnumber = null;
      char op, topop;
      int count = queue.count;
      for (int i = 0; i < count; i++)
      {
        object obj = queue.dequeue();
        if (obj is char)
        {
          op = (char)obj;
          if (_operatorstack.count == 0)
          {
            _operatorstack.push(op);
          }
          else
          {
            topop = (char)_operatorstack.peek();
            if (op == '(')
            {
              _operatorstack.push(op); // 左括号直接压入。不判断栈顶
            }
            else if (op == ')')
            {
              // 右括号压入前观察栈顶,若栈顶是左括号,则弹出栈顶的左括号
              // 否则弹出栈顶运算符,从数栈中弹出操作数进行运算,并将结果重新压入数栈,直到遇到左括号
              while ((topop = (char)_operatorstack.pop()) != '(')
              {
                complexnumber c1 = (complexnumber)_complexnumberstack.pop(); // 符号右边数
                complexnumber c2 = null; // 符号左边数
                if (_operators.istwonumoperator(topop))
                {
                  c2 = (complexnumber)_complexnumberstack.pop();
                }
                complexnumber c3 = _operators.compute(topop, c2, c1);
                _complexnumberstack.push(c3);
              }
            }
            else if (_operators.comparepriority(topop, op) <= 0)
            {
              // 若即将压入的运算符不是括号,则比较栈顶运算符和即将压入的运算符的优先级
              // 如果栈顶优先级高,则将栈顶运算符取出运算,直到栈顶优先级不大于其。
              while (_operatorstack.count != 0 && _operators.comparepriority((char)_operatorstack.peek(), op) <= 0)
              {
                topop = (char)_operatorstack.pop();
                complexnumber c1 = (complexnumber)_complexnumberstack.pop(); // 符号右边数
                complexnumber c2 = null; // 符号左边数
                if (_operators.istwonumoperator(topop))
                {
                  c2 = (complexnumber)_complexnumberstack.pop();
                }
                complexnumber c3 = _operators.compute(topop, c2, c1);
                _complexnumberstack.push(c3);
              }
              _operatorstack.push(op);
            }
            else
            {
              _operatorstack.push(op);
            }
          }
        }
        else if (obj is complexnumber)
        {
          complexnumber = (complexnumber)obj;
          _complexnumberstack.push(complexnumber);
        }

        if (queue.count == 0)
        {
          while (_operatorstack.count != 0)
          {
            topop = (char)_operatorstack.pop();
            complexnumber c1 = (complexnumber)_complexnumberstack.pop(); // 符号右边数
            complexnumber c2 = null; // 符号左边数
            if (_operators.istwonumoperator(topop))
            {
              c2 = (complexnumber)_complexnumberstack.pop();
            }
            complexnumber c3 = _operators.compute(topop, c2, c1);
            _complexnumberstack.push(c3);
          }
        }
      }

      return (complexnumber)_complexnumberstack.pop();
    }
  }

  // 3+4i解析成queue包含 3, +, 4i
  public class parser
  {
    private operators _operators = new operators();

    public queue<object> parse(string input)
    {
      input = input.replace(" ", "");
      if (input.startswith("-")) input = '0' + input;

      char[] arr = input.tochararray();
      queue<char> queuechar = new queue<char>();
      foreach (char x in arr)
      {
        queuechar.enqueue(x);
      }
      queue<object> queueresult = parsestringqueue(queuechar);
      return queueresult;
    }

    // 传入字符串队列,返回封装好的队列。
    // complexnumber对象或char类型运算符各占用一个结点
    private queue<object> parsestringqueue(queue<char> queue)
    {
      queue<object> secondq = new queue<object>();
      char c;
      stringbuilder sb = null;
      string temp;
      int count = queue.count;
      bool flag = false; // false表示允许创建新sb对象进行缓存数字字符串
      for (int i = 0; i < count; i++)
      {
        c = queue.dequeue();
        if (!_operators.contains(c))
        {
          // 如果扫描到的不是运算符,则将其加入到buffer尾部
          if (!flag)
          {
            flag = true;
            sb = new stringbuilder();
          }
          sb.append(c);
        }
        if (_operators.contains(c) || queue.count == 0)
        {
          // 如果扫描到的是运算符,则将缓冲区中的串加入队尾
          if (sb != null && flag == true)
          {
            temp = sb.tostring();
            try
            {
              if (temp.endswith("i"))
              {
                if (temp.length == 1)
                {
                  secondq.enqueue(new complexnumber(0, 1));
                }
                else
                {
                  // i前有数字则开出数字部分。
                  temp = temp.substring(0, temp.length - 1);
                  secondq.enqueue(new complexnumber(0, double.parse(temp)));
                }
              }
              else
              {
                secondq.enqueue(new complexnumber(double.parse(temp), 0));
              }
              sb = null;
              flag = false;
            }
            catch (exception e)
            {
              unityengine.debug.log("error " + e.tostring());
            }
          }
          // 如果是运算符,则最后将运算符放入队。
          if (_operators.contains(c))
          {
            secondq.enqueue(c);
          }
        }
      }

      return secondq;
    }
  }

  // 复数类,提供实数域虚数域,getset方法,加减乘除以及tostring()方法
  class complexnumber
  {
    private double _realpart; // 实数部分
    private double _imaginpart; // 虚数部分

    public complexnumber()
    {
      _realpart = 0.0;
      _imaginpart = 0.0;
    }
    public complexnumber(double r, double i)
    {
      _realpart = r;
      _imaginpart = i;
    }
    public complexnumber(complexnumber c)
    {
      _realpart = c.getrealpart();
      _imaginpart = c.getimaginarypart();
    }

    // get,set方法
    public double getrealpart()
    {
      return _realpart;
    }
    public double getimaginarypart()
    {
      return _imaginpart;
    }
    public void setrealpart(double d)
    {
      _realpart = d;
    }
    public void setimaginarypart(double d)
    {
      _imaginpart = d;
    }

    // 加
    public complexnumber complexadd(complexnumber c)
    {
      return new complexnumber(_realpart + c.getrealpart(), _imaginpart + c.getimaginarypart());
    }
    public complexnumber complexadd(double c)
    {
      return new complexnumber(_realpart + c, _imaginpart);
    }
    // 减
    public complexnumber complexminus(complexnumber c)
    {
      return new complexnumber(_realpart - c.getrealpart(), _imaginpart - c.getimaginarypart());
    }
    public complexnumber complexminus(double c)
    {
      return new complexnumber(_realpart - c, _imaginpart);
    }
    // 乘
    public complexnumber complexmulti(complexnumber c)
    {
      return new complexnumber(
      _realpart * c.getrealpart()
      - _imaginpart * c.getimaginarypart(),
      _realpart *
      c.getimaginarypart()
      + _imaginpart *
      c.getrealpart());
    }
    public complexnumber complexmulti(double c)
    {
      return new complexnumber(_realpart * c, _imaginpart * c);
    }
    // 除
    public complexnumber complexdivision(complexnumber c)
    {
      return new complexnumber((_realpart * c.getrealpart() + _imaginpart * c.getimaginarypart())
        / (c.getrealpart() * c.getrealpart() + c.getimaginarypart() * c.getimaginarypart())
        , (_imaginpart * c.getrealpart() - _realpart * c.getimaginarypart())
        / (c.getrealpart() * c.getrealpart() + c.getimaginarypart() * c.getimaginarypart()));
    }
    public complexnumber complexdivision(double c)
    {
      return new complexnumber(_realpart / c, _imaginpart / c);
    }
    // 幂
    public complexnumber complexpow(complexnumber c)
    {
      int pow;
      if (int.tryparse(c.getrealpart().tostring(), out pow))
      {
        complexnumber origin = new complexnumber(this);
        complexnumber multi = new complexnumber(this);
        for (int i = 0; i < pow - 1; i++)
        {
          origin = origin.complexmulti(multi);
        }
        return origin;
      }
      else
      {
        return complexpow(c.getrealpart());
      }
    }
    public complexnumber complexpow(double c)
    {
      return new complexnumber(math.pow(_realpart, c), 0.0);
    }
    // 最小值
    public complexnumber complexminimum(complexnumber c)
    {
      if (_realpart <= c.getrealpart()) return this;
      return c;
    }
    // 最大值
    public complexnumber complexmaximum(complexnumber c)
    {
      if (_realpart >= c.getrealpart()) return this;
      return c;
    }
    // 转int
    public complexnumber tofloorint()
    {
      _realpart = math.floor(_realpart);
      return this;
    }

    public override string tostring()
    {
      return "(" + _realpart + " + " + _imaginpart + " i" + ")";
    }
  }

  // 操作符类
  class operators
  {
    private char[][] _signoperator;

    public operators()
    {
      // 从上到下,优先级由高到低
      _signoperator = new char[4][];
      _signoperator[0] = new char[4];
      _signoperator[0][0] = '^';
      _signoperator[0][1] = 's'; // 最小值
      _signoperator[0][2] = 'b'; // 最大值
      _signoperator[0][3] = 'i'; // int值
      _signoperator[1] = new char[2];
      _signoperator[1][0] = '*';
      _signoperator[1][1] = '/';
      _signoperator[2] = new char[2];
      _signoperator[2][0] = '+';
      _signoperator[2][1] = '-';
      _signoperator[3] = new char[2];
      _signoperator[3][0] = '(';
      _signoperator[3][1] = ')';
    }

    // 比较操作符优先级
    public int comparepriority(char firstsign, char secondsign)
    {
      int priorityf = 0, prioritys = 0;
      for (int i = 0; i < _signoperator.length; i++)
      {
        foreach (char x in _signoperator[i])
        {
          if (firstsign == x)
          {
            priorityf = i;
          }
          if (secondsign == x)
          {
            prioritys = i;
          }
        }
      }

      return (priorityf - prioritys);
    }

    // 是否是需要两个参数的操作符
    public bool istwonumoperator(char op)
    {
      if (op == 'i') return false;
      return true;
    }

    public bool contains(char x)
    {
      if (x == '(' || x == ')')
      {
        unityengine.debug.logerror(x + "为中文字符,请改为英文字符");
      }

      foreach (char[] arr in _signoperator)
      {
        foreach (char y in arr)
        {
          if (x == y)
          {
            return true;
          }
        }
      }
      return false;
    }

    public complexnumber compute(char op, complexnumber c1, complexnumber c2)
    {
      complexnumber result = null;
      switch (op)
      {
        case '+': result = c1.complexadd(c2); break;
        case '-': result = c1.complexminus(c2); break;
        case '*': result = c1.complexmulti(c2); break;
        case '/': result = c1.complexdivision(c2); break;
        case '^': result = c1.complexpow(c2); break;
        case 's': result = c1.complexminimum(c2); break;
        case 'b': result = c1.complexmaximum(c2); break;
        case 'i': result = c2.tofloorint(); break;
      }
      return result;
    }
  }
}

这篇文章就介绍到这了,希望能帮助到你。