0

I am trying to make a simple calculator with arrays in C#. Firstly I tried making it using two integers and one operator only and it worked well. Now I am trying to do so that the user can make the expression as long as they like. For example 7 * 7 + 1 / 50 instead of a simple 9 + 8 which includes only one operator and two integers. The problem is that whenever I type a long expression with multiple numbers and operators it only calculates the first 2 numbers with the first operator. What is a good fix for this problem ? Thanks in advance.

static void Main()
    {
        while (true)
        {
            Console.WriteLine("Write an expression with two numbers and an operator with space in-between, for example, 4 + 2");
            string expression;
            string[] array;
            string[] array1;
            expression = Console.ReadLine();
            array = expression.Split();
            array1 = Calculation(array);
            Console.WriteLine("Press ENTER to write a new expression.");
            Console.ReadLine();
            Console.Clear();
        }

    }
    static string[] Calculation(string[] arr)
    {
        double numLeft= 0.0;
        double numRight = 0.0;
        string sign = "";
        double result = 0.0;
        int index = 1;

        while (true)
        {
            numLeft = Convert.ToDouble(arr[0]);
            sign = Convert.ToString(arr[index]);
            numRight = Convert.ToDouble(arr[index + 1]);
            index = index + 2;
            if (sign == "+")
            {
                Console.Clear();
                Console.WriteLine();
                result= result + numLeft;
            }
            else if (sign == "-")
            {
                Console.Clear();
                result = result + numLeft;
                numLeft = 0 - numRight;
            }
            else if (sign == "*")
            {
                Console.Clear();
                numLeft = numLeft * numRight;
            }
            else if (sign == "/")
            {
                Console.Clear();
                numLeft = numLeft / numRight;
            }
            else
            {
                break;
            }
            result = result + numLeft;
            Console.WriteLine("Answer: {0}", result);
            return arr;
        }
        return arr;
    }
Martin Zahariev
  • 697
  • 1
  • 7
  • 6
  • How do you handle the different priority of operators? You know `/` and `*` are of higher priority than `+` and `-`. Implementing such a complex expression isn´t trivial and thus far too broad for a single question on SO. – MakePeaceGreatAgain Oct 21 '16 at 10:51
  • @HimBromBeere I haven't actually thought about it, to be honest and at this point I don't really have a solution for it. – Martin Zahariev Oct 21 '16 at 10:59
  • Here is a pretty good hand crafted math expression evaluator https://github.com/henon/PrimitiveCalculator – henon Nov 21 '20 at 23:00

4 Answers4

2

because you return the array at the end of the "while true", so only first 2 get calculated.

Also, this will not be correct. for example: 2 + 3 * 4 = 14, and not 20, like your calculator will calculate.

Noctis
  • 11,507
  • 3
  • 43
  • 82
0

How about this?

Split your operation string into pieces and fill a list with them;

7 * 7 + 1 / 50 => [7][*][7][+][1][/][50]

Then go through the list and solve the * and / operations. When you encounter one of the operators remove the operator element, the one before it and the one after it, and replace them with the result. Keep in mind that the list length changes.

first iteration => [49][+][1][/][50] second iteration => [49][+][0.02]

Then do the same for + and - operators first iteration => [49.02]

When you have only one element remaining in the list, that is your result.

Lidaranis
  • 765
  • 3
  • 9
  • well, if he's using arrays, he can't do that exactly, because the array size doesn't change. but other than that, yep. – Noctis Oct 21 '16 at 11:04
  • @Noctis you are right, i wrote it like this [][][] just to make it easier to read. He can go with a List<> or something.(or build a nea array every time..) – Lidaranis Oct 21 '16 at 11:06
  • building a new array would be wasteful (probably wouldn't matter for the case in hand, but very bad if you get into this habit :) ). plenty of options around. He asked why it's not working, I've given him the reason :) – Noctis Oct 22 '16 at 06:11
0

For simple computations there exists a method in .net:

public static int Compute(string operation)
{
    return new DataTable().Compute("7 * 7 + 1 / 50", null);
}

Source: C# Math calculator

If you really want to implement this I would suggest a recursive binary tree algorithm.

Pseudo-code: 1. Split incoming string on places where there is a mathematical operation symbol and turn in to a binary tree 2. Go through this tree and resolve operations that have a greater priority (* comes before +) 3. Recursion should return value of two child leafs and so on until it yields only one value to the main program

Community
  • 1
  • 1
Zoran Basic
  • 156
  • 1
  • 11
-1
using System;

namespace _2nd_A_recap
{
    class Program
    {
        static void Main(string[] args)
        {
            int result;
            int a = 20, b = 10;
            result = (a + b );
            Console.WriteLine("Addition Opertaor:" + result);
            result = (a - b);
            Console.WriteLine("Subtraction Operator:" + result);
            result = (a * b);
            Console.WriteLine("Multiplication Operator:" + result);
            result = (a / b);
            Console.WriteLine("Division Operator:" + result);
            result = (a % b);
            Console.WriteLine("Modulus Operator:" + result);
            Console.WriteLine("Press enter to end Calculator...");
            Console.ReadKey();
        }
    }
}
Minal Chauhan
  • 6,025
  • 8
  • 21
  • 41