【问题标题】:Calculating string from a text box with operator precedence从具有运算符优先级的文本框中计算字符串
【发布时间】:2015-03-03 12:10:13
【问题描述】:

按钮代码: 我的按钮中的所有代码都是用数字的字符串表示填充文本框。

    private void button9_Click(object sender, EventArgs e)
    {

        if ((screenBox.Text == "0") || (opr))
        {
            screenBox.Clear();

        }
        opr = false;
        screenBox.Text = screenBox.Text + button9.Text;
    }

运营商代码: 操作员代码做同样的事情。

    private void buttonAdd_Click(object sender, EventArgs e)
    {
        operation = buttonAdd.Text;
        screenBox.Text =screenBox.Text +" "+ operation +" ";

    }

等于: 现在,当我按下等于时。

    public void buttonEq_Click(object sender, EventArgs e)
    {

        operation = buttonEq.Text;
        screenBox.Text = " " + screenBox.Text + " " + operation;

        string splitUp;  //stores elements of the original string
        string expr = screenBox.Text;   //makes expr whatever is in textbox

        string[] ops;//makes array called ops

        ops = expr.Split( '(', ')', '^', '/', '*', '+', '-', '='); 
        //splits expr which contains the string input to the screenbox                             
        //using any operator as a token (unless i'm confused and you don't  
        //all them tokens with this method) 

        foreach(string op in ops)
        {
            splitUp = op;
            Console.WriteLine(op);
        }
        //string split up holds whatever is in op, which is a string that  
        //contains an element of ops, which is the array that indexes the  
        //elements of the original string
        //eg 5+5= in the text box would appear as        in the console.                      
                                                //5 
                                                //5

我现在应该如何解决这个问题,以便我的程序知道它在添加时已经拆分,所以它需要在 + 之前和之后添加两个数字(或 '*'、'/'、'-')但是在执行计算并收集该序列的总和之前,首先要检查运算符右侧的“(”“)”括号

我只想了解我应该采用哪种逻辑。

【问题讨论】:

  • 最好使用表达式解析器而不是自己构建。 Search for C# Expression parser
  • 我知道,但这是为大学工作,我认为我们不能包含图书馆。一直在寻找要实现什么样的逻辑,但还没有真正走多远……仍然,早期。

标签: c# visual-studio calculator


【解决方案1】:

好的,所以我对被告知只包含一个库而不是体验创建自己的解析器的学习曲线感到有点失望。

所以。它很长,而且我还没有高级解析器,但到目前为止它做了一些基本的事情,比如对我设置的优先顺序中的数字进行操作等。

所以我不会详细介绍,但基本上我会说对我了解有帮助的内容。

  1. 准备 你需要对堆栈、队列、列表、数组有基本的了解,并搜索如何构建一个标记化类(对于这个类,你需要了解 Enums “Token” 数据类型和获取函数)你需要研究“Shunting Yard Algorithm”和“Reverse Polish Notation”以及如何在编程中融入 HEAVILY

  2. 构建标记化类 一旦您了解了如何有效地对字符串进行标记,即获取输入字符串并对其进行编辑以包含适当的标记,或者实施一种技术,其中标记自动成为输入的一部分并且需要对原始字符串进行最少的编辑.您应该研究如何构建一个好的标记化类。并尝试一下。

2.5:没有错误 = 继续

3.Shunting Yard 和 Reverse Polish notation 将通过使用来自 Tokenization 类以及第 1 步但来自表单类的元素和数据类型来实现。

标记化类将包含优先关联等所有信息。

4.如果您的Shunting yard Algorithm在您的表单类中成功实现,您可以将反向波兰表示法合并到Shunting Yard Algorithm输出的运算符和操作数中

我是新手,很抱歉我无法详细解释,或者如果我犯了错误,请指出并纠正我!

【讨论】:

    猜你喜欢
    • 2014-01-30
    • 2011-07-07
    • 2021-10-25
    • 1970-01-01
    • 2020-08-22
    • 2015-03-20
    • 2014-03-25
    相关资源
    最近更新 更多