Calculation formula

I am trying to get a program that takes an equation from the user (in 1 line) and outputs the result. So far I am using indexof to search for the + sign and then Im trying to find the value of the number to the left and right of the + sign -

            string input = "5+4+6";
            while (input.Contains('+'))
            {
                Console.WriteLine(input.IndexOf("+"));

                string position1 = input.Substring(0, input.IndexOf("+"));
                int number1 = Convert.ToInt32(position1);

                String position2 = input.Substring(2, input.IndexOf("+"));
                int number2 = Convert.ToInt32(position2);

                int sum = (number1 + number2);

      

The problem with my code is that I am specifying the number on the left and converting it to int, whereas in real life the numbers in the equation will be inactive, maybe 2 + 4 or 3 + 5 + 6 + 4, for simplicity's sake, now Im trying to do + and -, then / and *.

Can anyone suggest code improvement or any help? I know there are other ways to calculate the formula like ncalc, but I would like to stick with this approach.

thank

+3


source to share


5 answers


From what you provided, if this is the expected input string

, you can do something like this:

string input = "5+4+6";
int result = 0;
while (input.Contains('+'))
{
    var numbers = input.Split('+');

    foreach(var num in numbers)
    {
        result += Convert.ToInt32(num);
    }
}

      



Something like this should work and you can substitute +

for any of the operators.

+3


source


If the only operator you need to worry about is +, you can simply use string.Split () to create an array of strings, then convert them to integers and sum them. You can simplify some of these even further with Linq.

string[] numbers = input.Split('+');
int sum = input.Select(n => int.Parse(n)).Sum();

      



You can even combine this into one statement

int sum = input.Split('+').Select(n => int.Parse(n)).Sum();

      

+2


source


Well, for educational purposes and for this particular case, you can use your own "manual" parsing approach.

But for real life, if you want to parse formulas, I recommend that you read about "Reverse Polish Notation" and Shunting Algorithm. This is the way you can parse any formulas without any restrictions on operations (you can implement this for "+" and then easily add operations "-", "*", "/" and even "sin", "cos ").

+2


source


To handle addition, subtraction, multiplication and division, and to take into account the order of operations ... I would look at the Shunting-Yard Algorithm . This will take an input expression that is specified as infix notation and convert it to reverse polish notation. There are many .NET implementations of the Shunting-Yard algorithm that you can take a look at.

Like everyone else, if the input contains only one type of operation, say addition, then you can use .Split('+')

and then parse each integer and add them together.

0


source


I am using the same priority as Excel. Work behind + - * /


.NET Fiddle

This only works with integers in the formula. Even if the return is double, to keep the division. If you want to accept double in try formula double.Parse

insteadint.Parse

=1+2*3/4-5+6*7/8-9

will receive -6.75.
First operations - 3/4 and 7/8
then 2 * 0.75 and 6 * 0.875
then 1.5 - 5 and 5.25 - 9
finally 1 + (-3.5) + (-3.75)

=1+2+3+4+5+6+7+8+9

- 45 =1-2-3-4

- -8
=1*2*3*4

is 24
=1/2/3/4

- 0.416667

public static void Main()
{
    int n;
    bool isNumeric;
    string input = "1+2*3/4-5+6*7/8-9";
    string[] addSplit = input.Split('+');
    double addTotal = 0;
    foreach (string addCode in addSplit)
    {
        isNumeric = int.TryParse(addCode, out n);
        if (isNumeric)
        {
            addTotal += n;
        }
        else
        {
            string[] addMinus = addCode.Split('-');
            double minusTotal = 0;
            bool firstMinus = true;
            foreach (string minusCode in addMinus)
            {
                isNumeric = int.TryParse(minusCode, out n);
                if (isNumeric)
                {
                    if (firstMinus) { 
                        minusTotal = n;
                        firstMinus = false;
                    }
                    else {
                        minusTotal -= n;
                    }
                }
                else
                {
                    string[] multySplit = minusCode.Split('*');
                    double multyTotal = 1;
                    foreach (string multyCode in multySplit)
                    {
                        isNumeric = int.TryParse(multyCode, out n);
                        if (isNumeric)
                        {
                            multyTotal *= n;
                        }
                        else
                        {
                            string[] divSplit = multyCode.Split('/');                               
                            int.TryParse(divSplit[0], out n);                               
                            double divTotal = n;    

                            for( int i = 1; i < divSplit.Length ; i++ ) {   
                                int.TryParse(divSplit[i], out n);
                                divTotal /= n;
                            }
                            multyTotal *= divTotal;                         
                        }
                    }
                    if (firstMinus) { 
                        minusTotal = multyTotal;
                        firstMinus = false;
                    }
                    else {
                        minusTotal -= multyTotal;
                    }   
                }
            }
            addTotal += minusTotal;
        }
    }
    Console.WriteLine("addTotal: " + addTotal);
}

      

0


source







All Articles