-2

I need to control operator precedence in textbox. It should be 17. How to fix it? enter image description here

user5695111
  • 111
  • 2
  • 13
  • 3
    Parenthesis around the multiplication. Code executes left to right. Also, in the future please show your actual code and not just an image. The URL to your image may go dead in the future. – Drew Kennedy Apr 17 '16 at 20:54
  • 2
    How to fix what? What is your code? What is the difficulty you're encountering when you try to improve it? – gturri Apr 17 '16 at 20:54
  • You haven't really shown us your code, but it seems likely that you'll need to go through the input multiple times to find the highest-precedence operators. – BJ Myers Apr 17 '16 at 20:57
  • Show the code, and not just as an image. Your code might parse the string `"2+3*5"` in some way, and it leads to the eventual calculation of `(2+3)*5`, not `2+(3*5)`. – Jeppe Stig Nielsen Apr 17 '16 at 21:00
  • 1
    I think you need to add code to support operator precedence. It's not like it forms out of thin air just because you wish it to. If you're dealing with infix notation, a simple stack-based approach should work quite well (and it gives you parentheses for free). – Luaan Apr 17 '16 at 21:01

1 Answers1

0

When you sort operators, make sure to provide custom IComparer

void Main()
{
var comparer = new OperatorComparer();
    var operators = new[] { '+', '-', '*', '/' };
    Array.Sort(operators,comparer);

}
public class OperatorComparer : IComparer
{
    public int Compare(object x, object y)
    {
        var xv = (char)x;
        var yv = (char)y;
        if (xv == '*' || xv == '/')
        {
            if(yv == '*' || yv == '/')
                return 0;
            else 
                return -1;
        }
        else if (yv == '+' || yv == '-')
            return 0;
        return 1;
    }
}

THis will help, but without seeing all of your code I still assume it cannot handle parenthesies. Look into AST building parsers, they will help to create real calculator functions.

Dmitriy
  • 638
  • 1
  • 6
  • 12