当前位置:编程学习 > C#/ASP.NET >>

栈的应用_表达式求值_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

补充:软件开发 , C# ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,