R
R
Ryuk1242020-10-26 14:21:16
C++ / C#
Ryuk124, 2020-10-26 14:21:16

How to add multiple numbers for a calculator?

I'm writing a calculator in C# (UWP), I can't figure out how to add/subtract/divide/etc several numbers, not 2. Now there is such a code (it can only count 2 numbers if you enter, for example, 3+3+3 , it will throw "System.FormatException: "Input string was not in a correct format."):

private void Result(object sender, RoutedEventArgs e)
        {
            if (Score.Text != "")
            {
                double result = 0;
                char[] textBoxCharred = (Score.Text.ToString()).ToCharArray();

                foreach(char i in textBoxCharred)
                {
                    switch (i)
                    {
                        case '+':
                            int a = Score.Text.IndexOf('+');
                            string l = "";
                            string c = "";
                            for (int b = 0; b < a; b++) {
                                l += textBoxCharred[b];
                            }
                            double nextTerm = Score.Text.Length;

                            for (int b = a + 1; b < nextTerm; b++)
                            {
                                c += textBoxCharred[b];
                            }

                            double term1 = Convert.ToDouble(l);
                            double term2 = Convert.ToDouble(c);

                            result = term1 + term2;
                            continue; 
                    }
                }


                Score.Text = result.ToString();
            }

I don't have any ideas at all, any suggestions?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vasily Bannikov, 2020-10-26
@vabka

1. Get rid of WPF and learn how to calculate strings, because your task is not tied to WPF in any way
2. The machine does what it was told, and not what the person wants - in this case, "find the index of the '+' sign in the string, break string into two parts to its index, parse numbers from those strings, add them"
3. google AST and reverse polish notation

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question