Jump to content

Array into a formula


smus

Recommended Posts

Elements of an array of a math formula look like this:

a = [1,'+',2,'-',3,'*',4,'/',5];

How do I perform all the arythmetic actions between those numbers. The array elements may be different, because they are added dynamically.

It would not be difficult if I didn't have to prioritize the actions (/,*,_,-). I tried using splice() method, but something goes wrong. Maybe I can somehow sort the elements according to the math actions priority?

Link to comment
Share on other sites

eval() works in this case, but I am not sure what the right priority is (operator precedence) in Javascript. Some websites has info that divistion(/) has the highest priority then goes multiplication, addition and subtraction. That is strange, because usually multiplication is the first.

1-2+3*4/5 = 1.4 according to JS compliler (/ then * then - then +, no idea why it counts like that)

1-2+3*4/5 = 1.6 according to Windows Calc (I guess, it counts without any priority)

1-2+3*4/5 = -3.4 if we use the correct operator precedence (* / + -)

What I was taught in high school is that the correct precedence must be: * / + - Never thought that there might be another order in programming languages.

Edited by smus
Link to comment
Share on other sites

Multiplication and division have the same precedence, addition and subtraction have the same precedence. When two operators of the same precedence are found, the leftmost operation is done first.

Link to comment
Share on other sites

13 hours ago, Ingolme said:

Multiplication and division have the same precedence, addition and subtraction have the same precedence. When two operators of the same precedence are found, the leftmost operation is done first.

Exactly, right. The precedence goes pair(* and /) over pair(+ and -) and the Win Calc must be set to a kind of formula mode to use precedence order, otherwise it counts numbers from left to right as they are. Thanks!

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...