How to properly parse numbers in an arithmetic expression, differentiating positive and negative ones?

后端 未结 1 1248
离开以前
离开以前 2021-01-22 06:04

I have an assignment in my Data Structures class in which I have to program a calculator that solves arithmetic expressions with the 4 basic operations and parenthesis, the inpu

1条回答
  •  天涯浪人
    2021-01-22 06:44

    That is the problem called "unary minus" and can in your case (no variables) get solved by substitution.

    The operator - is an unary minus if it is

    • preceded by a left parenthesis
    • preceded by another operator
    • the first character of the input

    Now instead of storing a - you store a different character like, say m and assign it a higher precedence than the other operators (or the same as the exponentiation operator if you have one).

    Another tip: don't use spaces to indicate anything, an arithmetic expression must work without any spaces or it is not correct.

    0 讨论(0)
提交回复
热议问题