Jump to content

How would I do this to make a simple calculator?


foobarbaz

Recommended Posts

hi

 

I was making a simple calculator but am stumped on how to allow it to have more than one argument in the equation.. It is simple I guess to explode it to get one:

 

$equation = "10/2"; 
$eq = explode('/', $equation);
$result = $eq[0] / $eq[1]

 

but how would I be able to do something like this:

 

$equation="3+4/2*2+1";
????

 

I just cannot wrap my head around it, thanks

Well first you need to do the order of calculation, BEDMAS: Brackets, Exponents, Divide, Multiply, Add, Subtract.

 

But that can get really deep.

 

For the equation you gave me, i would first sanitize it o it only contained numbers, brackets, and arithmatical components (*/-+ etc).

 

Then just use eval, and let php do the hard part:

 

$equation = "2+4*6+(2/2)-4";
eval("$answer = ".$equation.";");

 

the result will be in the variable $answer.

 

-cb-

I actually need to apply the BC calc stuff to keep it arbitrary precision, The eval thing seemed perfect, but It'll only help to a level.. Maybe this project is too hard to do, grr. I might need to implement stacks or something.

implementing a stack may not be a bad idea, and would definitely make the coding easier if you are unable to use eval. A quick google search for PHP stack retrieved: http://www.phpclasses.org/browse/file/2710.html

 

 

note: I don't have any experience with that class, so I can not recommend it fully. A more complete search would probably be necessary if you don't plan on implementing it your self. If you do plan to implement it, I don't imagine you would need a very robust stack, more of a array wrapper class that acts "stack-like". Also, a stack class is nice to have around. You could make a nice one, and use it in a lot of places.

 

Unfortunately, there is no STL equivalent for PHP (though it has no templates, so I guess the T would be kind of weird) which would have some standardized data structures and algorithms, but this is life I suppose. Good luck on your project.

 

after you make a stack, you could then turn the equation to a postfix (or is it prefix?) and evaluate it.

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.