Revision c197e9d8-a2fb-4e19-a60f-16823affeedc - Code Review Stack Exchange

In a comment you state that you "was trying to follow PEMDAS", that is Parenthesis, Exponents, Multiply and Divide, Addition and Subtraction, which sounds like a good track to follow. However you would benefit from preprocessing your string into an array or list consisting of two types of elements, and that is numbers and tokens (like `(`, `)`, `^`, `*`, `/`, `+`, `-`).

When this array is created you have a much easier task of walking through the array (or list) and simplify it step by step, going through the PEMDAS. With a proper list, you find your wanted operator, and then pick the number in front and after the operator and calculate it. Replace the three elements you justed calculated, and repeat simplification...

By the way, what I've just described is a simple variant of building an Abstract Syntax Tree (consisting of numbers and tokens), which you then parse into the expression you want to calculate. The great advantage of doing this in these two steps is that you can focus your attention on either picking numbers or tokens, or afterwards actually simplifying/calculating according to PEMDAS.

Sorry, for not providing actual code, but you seem to know enough to understand how to walk through the list once to extend the numbers and tokens. Afterwards, keep manipulating the array (or list), which hopefully also is known operations.

AltStyle によって変換されたページ (->オリジナル) /