Duncan Palmer
Duncan Palmer

Reputation: 2913

Calculator - Allowing negative numbers in calculation

For a practice assignment I need to create a calculator which can:

I have made everything work apart from the handling negative numbers and I dont really know how to do such a thing and thought you may be able to help. Here is my current solving code:

public decimal getResult(string equation)
{
   //parse a equation as a string and solve it
   List<string> numbers = input.Split(opSplit, StringSplitOptions.RemoveEmptyEntries).ToList<string>();
   List<string> operators = input.Split(numSplit, StringSplitOptions.RemoveEmptyEntries).ToList<string>();

   //remove any decimals from operators list
   for (int i = 0; i < operators.Count; i++)
   {
      if (operators[i] == ".")
      {
         operators.RemoveAt(i);
      }
   }

   //set total to first values in numbers then remove in from list
   decimal total = decimal.Parse(numbers[0]);
   numbers.Remove(total.ToString());

   int count = 0;

   foreach(string s in numbers) {
      decimal val = decimal.Parse(s);
      string current_operator = operators[count];
      MessageBox.Show(current_operator);
      switch (current_operator)
      {
         case "+":
            total += val;
         break;
         case "-":
            total -= val;
         break;
         case "x":
            total *= val;
         break;
         case "/":
            total /= val;
         break;
      }

      if (count != operators.Count-1)
      {
         count++;
      }
   }
   return total;
}

My equations are inputed in this format.

Upvotes: 0

Views: 3794

Answers (1)

Jeroen Vannevel
Jeroen Vannevel

Reputation: 44439

First of all: right now you're not taking into account the order of operations, which is a very bad idea.

I assume you want to do something like this: -3 + -5, correct?

Here are a few assumptions that you can make:

  • Do not set the initial value equal to the first value

Set total = 0 instead. That way, if you start with -5, you have the equation 0 - 5 which is already correct and there's no hassle with the initial value.

  • Simplify the mathematical operations

-3 + -5 is the same as 0 - 3 - 5. Take advantage of this: parse your operators and check if you have two operators following eachother. If you have this: simplify the operation and you're good to go.

For good measure:

+-------------+
| op | op | = |
+-------------+
| +  | +  | + |
| +  | -  | - |
| -  | +  | - |
| -  | -  | + |
+-------------+

Upvotes: 3

Related Questions