Negative value in string based C # calculator

I am relatively new to programming and am currently working on a string based calculator in C #. Many of them work fine, but I have problems with negative odds. My calculator engine is always looking for the next operator and calculates accordingly, so the problem is that if I want to calculate "-5 + 6", the first operation is "-5", but it obviously cannot be calculated. How can I separate the operator and the coefficient? What I came up with so far (a small piece of all the code)

if (nextOperation.Contains("+"))
        {
            string firstOperationResult = Calculate(nextOperation.Split('+').ToList(), "+")[0];
            string partialFormulaReplacement = partialFormula.Replace(nextOperation, firstOperationResult);

            return CalculateDashOperation(partialFormulaReplacement);
        }

        else if (nextOperation.Contains("-") && nextOperation.IndexOf("-") > 0)
        {
            string resultOfFirstOperation = Calculate(nextOperation.Split('-').ToList(), "-")[0];
            string partialFormulaReplacement = partialFormula.Replace(nextOperation, resultOfFirstOperation);

            return CalculateDashOperation(partialFormulaReplacement);
        }
        //added
        else if (nextOperation.Contains("-") && nextOperation.IndexOf("-") == 0)
        {
            //what to do
        }
        //added
        return partialFormula;
+4
source share
3 answers

"- 5" "0-5", , . , + -.

"-5", 0 Calculate, :

Calculate(new List<string>{"0", nextOperation[1]}, "-")

, , , , , .

+3

. : nextOperation - , "1 * -6 + 6"

, "" . , , ( python) .

.

0

Use the NCalc library:

Do not reinvent the wheel, * and / priorities are already implemented.

Simple expressions

Expression e = new Expression("2 + 3 * 5"); Debug.Assert(17 == e.Evaluate());

Controls the math functionality from System.Math

Debug.Assert(0 == new Expression("Sin(0)").Evaluate()); Debug.Assert(2 == new Expression("Sqrt(4)").Evaluate()); Debug.Assert(0 == new Expression("Tan(0)").Evaluate());

0
source

Source: https://habr.com/ru/post/1618275/


All Articles