4

I'm relatively new to programming, and I'm currently working on a C# string based calculator. A lot of it works fine already, but I'm having problems with negative coefficients. My calculator engine always looks 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 can't be calculated. How can I separate operator and coefficient? What I've come up with so far (small extract of the whole 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;
tweedledum11
  • 121
  • 9
  • "-" isn't part of the number, it's the unary inverse operator. – Scott M. Dec 02 '15 at 11:52
  • You should check [RVP](https://en.wikipedia.org/wiki/Reverse_Polish_notation) – Dominik S Dec 02 '15 at 11:52
  • -5 is the same as 5-5-5, +5 would ignore the + but what about --5 or ++5 ?, I think double operators screws your .Contains().. Are you meaning to cater for double operands? – Paul Zahra Dec 02 '15 at 11:55
  • the problem is that I split my input string at '-', so the result of that split with --5 would be null and -5 right? – tweedledum11 Dec 02 '15 at 11:59
  • Perhaps you could introduce an evaluation process, where you would get the operands and the next number and calculate it's real value... e.g. 5++5 so you would grab ++5 and evaluate it to -5... or perhaps you could scan the string for double operands and evaluate them, then scan the string again etc – Paul Zahra Dec 02 '15 at 12:02
  • @tweedledum11 As the saying goes, unless it's purely a learning process don't reinvent the wheel... re: MiseryInDevice answer: http://ncalc.codeplex.com/ – Paul Zahra Dec 02 '15 at 12:05
  • It is exactly that though, the goal being that I learn to deal with strings and some C# basics, so I'm supposed to find a way to work with strings only. – tweedledum11 Dec 02 '15 at 12:10
  • Wht about using regular expressions ? then parse the numbers and always sum them ? – L.Trabacchin Dec 02 '15 at 12:16

3 Answers3

3

"-5" can be treated as meaning "0-5", so you could say there's an implicit zero if you see an operand in the first position of the string. Note that this approach will only work for the operators + and -.

As for the problem of attempting to calculate "-5" again, I suggest you use the 0 as an argument to your Calculate function, rather than prepending it to the string you're processing:

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

Also, as has been pointed out in the comments, this approach will not cover all possible cases, and if this isn't an academic exercise then there are solutions out there that already solve this problem.

Adam H
  • 1,523
  • 11
  • 21
  • I thought of that as well and added a 0 to the beginning if the index of "-" was 0, but the result of that partial calculation is -5, that partial result replaces "0-5" and then it tries to calculate -5 again. – tweedledum11 Dec 02 '15 at 11:57
  • that's one way to think about it, but that can only apply to the beginning and only on - and +. Being more specific would help this answer. – Scott M. Dec 02 '15 at 11:57
0

The sample code looks a little short. But let's try to suggest: nextOperation is a string containing something like "1 * -6 + 6"

In order to evaluate this expression yout have to 'encrypt' your string first. The topic you are looking for is parenthesis A nice explanation of the basic (in python) can be found here.

But this question is already answered here.

Community
  • 1
  • 1
SolvedForHome
  • 152
  • 1
  • 15
  • Exactly something like that, yes. The things is, every other calculation works fine, and I have methods for calculating the paranthesis arithmetic first and returning a calulation without brackets, a method for finding the next operator/operation, seperate classes for each operator, how would paranthesis fit into this? – tweedledum11 Dec 02 '15 at 12:13
  • Well, the basic idea is, that you split and split your string until you have only single coefficients. So "-5" is and end of the recursive parenthesis function and thus can be handles as one. – SolvedForHome Dec 02 '15 at 12:16
0

Use NCalc Library:

Dont reinvent wheel, * and / priorities is already implemented.

Simple expressions

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

Handles mathematical functional 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());

Igor Quirino
  • 1,187
  • 13
  • 28