程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> 棧的應用_表達式求值_C#實現

棧的應用_表達式求值_C#實現

編輯:C#入門知識

[參考文獻:嚴蔚敏.數據結構(C語言版)]

表達式求值是程序設計語言編譯中的一個最基本問題,它的實現是棧應用的一個典型例子.

搞了一天,有相關的好的算法請大家傳上來,一起分享.

表3.1: 定義了算符之間的優先關系:

\

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;

namespace EvaluateExpression
{
    class EvaluateExpression
    {
        private static string  Precede(string  t1, string  t2)    //根據表3.1,判斷兩符號的優先關系
        {
            string f = string.Empty;
            switch (t2)
            {
                case "+":
                case "-":
                    if (t1 == "(" || t1 == "#")
                        f = "<";
                    else
                        f = ">";
                    break;

                case "*":
                case "/":
                    if (t1 == "*" || t1 == "/" || t1 == ")")
                        f = ">";
                    else
                        f = "<";
                    break;
                case "(":
                    if (t1 == ")")
                        throw new ArgumentOutOfRangeException("表達式錯誤");
                    else
                        f = "<";
                    break;
                case ")":
                    switch (t1)
                    {
                        case "(": f = "="; break;
                        case "#": throw new ArgumentOutOfRangeException("表達式錯誤");
                        default: f = ">"; break;
                    }
                    break;
                case "#":
                    switch (t1)
                    {
                        case "#": f = "="; break;
                        case "(": throw new ArgumentOutOfRangeException("表達式錯誤");
                        default: f = ">"; break;
                    }
                    break;
            }
            return f;
        }
        private static bool In(string  c)    //判斷c是否為運算符
        {
           switch(c)
           {
              case"+":
              case"-":
              case"*":
              case"/":
              case"(":
              case")":
              case"#":  return true ; 
              default:  return false ;
   &n

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved