从具有运算符优先级的文本框中计算字符串

本文关键字:计算 字符串 文本 运算符 优先级 | 更新日期: 2024-09-23 15:18:21

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

    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

我现在应该如何处理这个问题,以便我的程序了解它在加法时已经分裂,所以它需要在加法之前和之后加上两个数字+(或'*','/','-'),但在执行计算和收集该序列的和之前,要检查运算符右侧的"(")"括号

我只想知道我应该遵循什么样的基本逻辑。

从具有运算符优先级的文本框中计算字符串

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

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

所以我不会详细介绍,但基本上我会说什么对我知道有帮助。

  1. 准备您需要对Stacks、Queues、Lists、Arrays和search有基本的了解,并了解如何构建一个令牌化类(对于这个类,您需要了解Enums"Token"数据类型并获得函数)。您需要研究"Shutting Yard Algorithm"answers"Reverse Polish Notation"&如何结合在编程HEAVILLY

  2. 生成令牌化类一旦您了解了如何有效地将字符串标记化,也就是说,获取一个输入字符串,然后编辑它以包含适当的标记,或者实现一种技术,其中标记自动成为输入的一部分,并且需要对原始字符串进行最小的编辑。你应该研究如何构建一个好的代币化类。并尝试。

2.5:无错误=继续

3.分流场和反向抛光表示法将通过使用来自令牌化类以及步骤1但来自表单类的元素和数据类型来实现。

令牌化类将包含优先级关联性等的所有信息。

4.如果你的调车场算法在你的form类中成功实现,那么你就可以将反向抛光符号结合到调车场算法输出的运算符和操作数中

我是一个新手,很抱歉我不能详细解释,或者如果我犯了错误,请突出并纠正我!