0

I am a student and got a task where I will have to make a program that solves first-grade equations. I will start of by making a textbox where I can write down different numbers of all the arithmetics, for example, 3+4*8 (it doesn't have to follow the priority rules) and then when I press the "go" button I get the answer.

I tried using the split method from this question/answer: C# read and calculate multiple values from textbox and it worked for addition but then I tried to use the same script and change it up a little to make it work for multiplication and subtraction but it did not work.

The scripts that I have tried are:

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

        int intSumma = 0;

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

Also tried using switch (+) after the split but it did not work since there is not + left after te splitt

Any Idea on how I can make a textbox that calculates everything inside of it? My teacher gave me a tip to use the split method and case method together.

arradj
  • 1
  • 2
  • Can you show us the code you have so far, please? – swatsonpicken May 20 '20 at 14:29
  • Have you had any luck splitting a string giving it a list of all the operators? like `+`, `-`, `*`, etc. Using this variant of [String.Split](https://learn.microsoft.com/en-us/dotnet/api/system.string.split?view=netcore-3.1#System_String_Split_System_Char___) – Wyck May 20 '20 at 14:31
  • If you want to do it sophisticated, you can look in to lexical analysis, parsing and interpreters, especially because you have to deal with operator precedence. But if this is way beyond your skill level, start by splitting the string by spaces, and try to figure out a way to parse the parameters do doubles and recognize the operators. – L01NL May 20 '20 at 14:40
  • @swatsonpicken, I will edit the question and add the code :) – arradj May 20 '20 at 15:13

3 Answers3

1

Without giving the answer overtly, I would suggest that you keep a variable for the accumulator, operator, and operand. From there you can use a for loop to keep reading until you've evaluated all of the expression, then return the accumulator.

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 '+', '-', '*', '/'
    ...
}
Nate Zaugg
  • 4,202
  • 2
  • 36
  • 53
0

Change below line of code from this article C# read and calculate multiple values from textbox like this:

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

Replace above line with below line

 string[] parts = textBox1.Text.Split('+','*','-');
Modus Tollens
  • 5,083
  • 3
  • 38
  • 46
Always_a_learner
  • 1,254
  • 1
  • 8
  • 16
  • thank you for your answer, it now splits the numbers when writing /, +, * or - but it still uses addition when calculating because of the rest of the string, should I maybe use a switch after splitting them up and then give each one of them the right way to calculate? – arradj May 20 '20 at 15:08
  • @arradj use switch case after split to do calculation. do not forget to vote it – Always_a_learner May 20 '20 at 15:17
  • 2
    @user13422309 Please don't ask for votes in posts and/or comments. People might even downvote your posts for that. – Modus Tollens May 20 '20 at 15:20
0

One thing that should help you with creating a calculator like this is reversed Polish notation. Accepted answer to this question is a working calculator that can handle order of operations etc.

Code from mentioned post:

    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");                                          
        }
    }
}
Jarek Danielak
  • 394
  • 4
  • 18
  • thanks for the answer, I did not really understand the script so I will have to read more about that and ask my teacher for a translation so I understand what different lines do, and then I will try it out. :) – arradj May 20 '20 at 15:12