簡體   English   中英

C# 從文本框中計算多個值

[英]C# calculate multiple values from textbox

我是一名學生,我接到了一個任務,我必須編寫一個程序來解決一年級的方程。 我將首先創建一個文本框,我可以在其中寫下所有算術的不同數字,例如 3+4*8(它不必遵循優先級規則),然后當我按下“開始”按鈕時我得到了答案。

我嘗試使用此問題/答案中的拆分方法: C# 從文本框中讀取並計算多個值,它適用於加法,但后來我嘗試使用相同的腳本並稍微改變它以使其適用於乘法和減法,但它不工作。

我嘗試過的腳本是:

string[] parts = tbxTal.Text.Split('+');

        int intSumma = 0;

        foreach (string item in parts)
        {
            intSumma = intSumma + Convert.ToInt32(item);
        }
        lblSvar.Text = intSumma.ToString();

還嘗試在拆分后使用開關(+),但它不起作用,因為在拆分后沒有 +

關於如何制作一個計算其中所有內容的文本框的任何想法? 我的老師給了我一個技巧,讓我可以同時使用拆分法和案例法。

在不公開給出答案的情況下,我建議您為累加器、運算符和操作數保留一個變量。 從那里您可以使用 for 循環繼續閱讀,直到您評估了所有表達式,然后返回累加器。

double Evaluate(string expression) {
    double accumulator = 0;
    double operand = 0;
    string operator = string.Empty;
    int index = 0;

    while (index < expression.Length) {
        operand = ExtractNextNumericValue(ref index, expression);
        operator = ExtractNextOperator(ref index, expression);

        // We now have everything we need to do the math
        ...
    }
    return accumulator;
}

public double ExtractNextNumericValue(ref index, string expression) {
    // Use IndexOf on the string, use the index as a start location
    // Make sure to update ref to be at the end of where you extracted your value
    // You know that the value will come before an operator, so look for '+', '-', '*', '/'
    ...
}

從本文中更改以下代碼行C# 從文本框中讀取並計算多個值,如下所示:

string[] parts = textBox1.Text.Split('+');

用下面的行替換上面的行

 string[] parts = textBox1.Text.Split('+','*','-');

可以幫助您創建像這樣的計算器的一件事是反向波蘭表示法 這個問題的公認答案是一個可以處理操作順序等的工作計算器。

來自提到帖子的代碼:

    static void Main(string[] args)
    {
        String str = "5 + ( ( 1 + 2 ) *  4 ) −3";
        String result=LengyelFormaKonvertalas(str);
        Console.WriteLine(result.ToString());
        Console.ReadLine();
    }

    static String LengyelFormaKonvertalas(String input) // this is the rpn method
    {
       Stack stack = new Stack();
       String str = input.Replace(" ",string.Empty);
       StringBuilder formula = new StringBuilder();
       for (int i = 0; i < str.Length; i++)
       {
           char x=str[i];
           if (x == '(')
               stack.Push(x);
           else if (IsOperandus(x)) // is it operand
           {
               formula.Append(x);
           }
           else if (IsOperator(x))  // is it operation
           {
               if (stack.Count>0 && (char)stack.Peek()!='(' && Prior(x)<=Prior((char)stack.Peek()) )
               {
                   char y = (char)stack.Pop();
                   formula.Append(y);
               }
               if (stack.Count > 0 && (char)stack.Peek() != '(' && Prior(x) < Prior((char)stack.Peek()))
               {
                   char y = (char)stack.Pop();
                   formula.Append(y);
               }
               stack.Push(x);
           }
           else
           {
              char y=(char)stack.Pop();
              if (y!='(')
              {
                  formula.Append(y);
              }
           }
       }
       while (stack.Count>0)
       {
           char c = (char)stack.Pop();
           formula.Append(c);
       }
       return formula.ToString();
    }

    static bool IsOperator(char c)
    {
        return (c=='-'|| c=='+' || c=='*' || c=='/');
    }
    static bool IsOperandus(char c)
    {
        return (c>='0' && c<='9' || c=='.');
    }
    static int Prior(char c)
    {
        switch (c)
        {
            case '=':
                return 1;
            case '+':
                return 2;
            case '-':
                return 2;
            case '*':
                return 3;
            case '/':
                return 3;
            case '^':
                return 4;
            default:
                throw new ArgumentException("Rossz paraméter");                                          
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM