真实的国产乱ⅩXXX66竹夫人,五月香六月婷婷激情综合,亚洲日本VA一区二区三区,亚洲精品一区二区三区麻豆

成都創(chuàng)新互聯(lián)網(wǎng)站制作重慶分公司

怎么在C#中利用棧實(shí)現(xiàn)加減乘除運(yùn)算

這期內(nèi)容當(dāng)中小編將會(huì)給大家?guī)?lái)有關(guān)怎么在C#中利用棧實(shí)現(xiàn)加減乘除運(yùn)算,文章內(nèi)容豐富且以專業(yè)的角度為大家分析和敘述,閱讀完這篇文章希望大家可以有所收獲。

陽(yáng)西ssl適用于網(wǎng)站、小程序/APP、API接口等需要進(jìn)行數(shù)據(jù)傳輸應(yīng)用場(chǎng)景,ssl證書未來(lái)市場(chǎng)廣闊!成為創(chuàng)新互聯(lián)公司的ssl證書銷售渠道,可以享受市場(chǎng)價(jià)格4-6折優(yōu)惠!如果有意向歡迎電話聯(lián)系或者加微信:028-86922220(備注:SSL證書合作)期待與您的合作!

   類Parser   的parse方法,比如給一個(gè)“3+4i”的字符串,返回給你一個(gè)3個(gè)結(jié)點(diǎn)的隊(duì),隊(duì)列第一個(gè)元素是一個(gè)ComplexNumber對(duì)象,實(shí)數(shù)域?yàn)?,隊(duì)列的第二個(gè)元素是“+”號(hào),隊(duì)列第三個(gè)元素是一個(gè)ComplexNumber對(duì)象,實(shí)數(shù)域?yàn)?,虛數(shù)域?yàn)?。

    類Operators    用于測(cè)試字符是否是運(yùn)算符,用來(lái)進(jìn)行控制運(yùn)算,比較運(yùn)算符優(yōu)先級(jí)....

    類Handler   給一個(gè)字符串,他幫你處理,返回給你一個(gè)結(jié)果。其實(shí)就是調(diào)一下Parser類的方法去解析一下字符串,然后算一下結(jié)果,然后返回結(jié)果。

 類ComplexNumber,就是復(fù)數(shù)類啊,不用說(shuō)了,提供實(shí)數(shù)域虛數(shù)域,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;
		}
		
		//傳入字符串隊(duì)列,返回封裝好的隊(duì)列。
		//ComplexNumber對(duì)象或char類型運(yùn)算符各占用一個(gè)結(jié)點(diǎn)
		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表示允許創(chuàng)建新SB對(duì)象進(jìn)行緩存數(shù)字字符串
			for(int i=0;i

Don_Yao整合修復(fù)一些bug后的代碼

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

// 解析計(jì)算字符串公式
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 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); // 左括號(hào)直接壓入。不判斷棧頂
            }
            else if (op == ')')
            {
              // 右括號(hào)壓入前觀察棧頂,若棧頂是左括號(hào),則彈出棧頂?shù)淖罄ㄌ?hào)
              // 否則彈出棧頂運(yùn)算符,從數(shù)棧中彈出操作數(shù)進(jìn)行運(yùn)算,并將結(jié)果重新壓入數(shù)棧,直到遇到左括號(hào)
              while ((topOp = (char)_operatorStack.Pop()) != '(')
              {
                ComplexNumber c1 = (ComplexNumber)_complexNumberStack.Pop(); // 符號(hào)右邊數(shù)
                ComplexNumber c2 = null; // 符號(hào)左邊數(shù)
                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)
            {
              // 若即將壓入的運(yùn)算符不是括號(hào),則比較棧頂運(yùn)算符和即將壓入的運(yùn)算符的優(yōu)先級(jí)
              // 如果棧頂優(yōu)先級(jí)高,則將棧頂運(yùn)算符取出運(yùn)算,直到棧頂優(yōu)先級(jí)不大于其。
              while (_operatorStack.Count != 0 && _operators.ComparePriority((char)_operatorStack.Peek(), op) <= 0)
              {
                topOp = (char)_operatorStack.Pop();
                ComplexNumber c1 = (ComplexNumber)_complexNumberStack.Pop(); // 符號(hào)右邊數(shù)
                ComplexNumber c2 = null; // 符號(hào)左邊數(shù)
                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(); // 符號(hào)右邊數(shù)
            ComplexNumber c2 = null; // 符號(hào)左邊數(shù)
            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 Parse(string input)
    {
      input = input.Replace(" ", "");
      if (input.StartsWith("-")) input = '0' + input;

      char[] arr = input.ToCharArray();
      Queue queueChar = new Queue();
      foreach (char x in arr)
      {
        queueChar.Enqueue(x);
      }
      Queue queueResult = ParseStringQueue(queueChar);
      return queueResult;
    }

    // 傳入字符串隊(duì)列,返回封裝好的隊(duì)列。
    // ComplexNumber對(duì)象或char類型運(yùn)算符各占用一個(gè)結(jié)點(diǎn)
    private Queue ParseStringQueue(Queue queue)
    {
      Queue secondQ = new Queue();
      char c;
      StringBuilder sb = null;
      string temp;
      int count = queue.Count;
      bool flag = false; // false表示允許創(chuàng)建新SB對(duì)象進(jìn)行緩存數(shù)字字符串
      for (int i = 0; i < count; i++)
      {
        c = queue.Dequeue();
        if (!_operators.Contains(c))
        {
          // 如果掃描到的不是運(yùn)算符,則將其加入到buffer尾部
          if (!flag)
          {
            flag = true;
            sb = new StringBuilder();
          }
          sb.Append(c);
        }
        if (_operators.Contains(c) || queue.Count == 0)
        {
          // 如果掃描到的是運(yùn)算符,則將緩沖區(qū)中的串加入隊(duì)尾
          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前有數(shù)字則開出數(shù)字部分。
                  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());
            }
          }
          // 如果是運(yùn)算符,則最后將運(yùn)算符放入隊(duì)。
          if (_operators.Contains(c))
          {
            secondQ.Enqueue(c);
          }
        }
      }

      return secondQ;
    }
  }

  // 復(fù)數(shù)類,提供實(shí)數(shù)域虛數(shù)域,getset方法,加減乘除以及toString()方法
  class ComplexNumber
  {
    private double _realPart; // 實(shí)數(shù)部分
    private double _imaginPart; // 虛數(shù)部分

    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;
    }
    // 轉(zhuǎn)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()
    {
      // 從上到下,優(yōu)先級(jí)由高到低
      _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] = ')';
    }

    // 比較操作符優(yōu)先級(jí)
    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);
    }

    // 是否是需要兩個(gè)參數(shù)的操作符
    public bool IsTwoNumOperator(char op)
    {
      if (op == 'i') return false;
      return true;
    }

    public bool Contains(char x)
    {
      if (x == '(' || x == ')')
      {
        UnityEngine.Debug.LogError(x + "為中文字符,請(qǐng)改為英文字符");
      }

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

上述就是小編為大家分享的怎么在C#中利用棧實(shí)現(xiàn)加減乘除運(yùn)算了,如果剛好有類似的疑惑,不妨參照上述分析進(jìn)行理解。如果想知道更多相關(guān)知識(shí),歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。


標(biāo)題名稱:怎么在C#中利用棧實(shí)現(xiàn)加減乘除運(yùn)算
本文地址:http://weahome.cn/article/iihjge.html

在線咨詢

微信咨詢

電話咨詢

028-86922220(工作日)

18980820575(7×24)

提交需求

返回頂部