makko wrote:
Hello,
anyone know how to writre a program that take a commandline formula
and prints the calculated result? example;
$program 1+(2x3(3/2))-8
reagrds;
Makkko
Yes.
I have done it in several languages (not C). Kruse's book "Data Structures and
Program Design" develops a tree-based parser in Pascal. I don't recall whether
or not it is recursive descent, but I don't think so.
My own formula parsers were all recursive descent and used a stack of pointers
into the input string, rather than a parse tree. So it was easy enough to
do it that way. (I am no guru: if I could, you can.)
One thing I hope you have mastered already is RPN ("reverse Polish") or postfix
notation; you should understand why you need to rearrange an algebraic formula
into this form before you can evaluate it.
You might also look at the "dragon book" (Alfred V. Aho, Ravi Sethi, Jeffrey
D. Ullman, "Compilers: principles, techniques, and tools"). They discuss some
important aspects of compiler design and rule-based programs in general, in
particular the BNF notation for expressing rules. If you can state the rules
for your formula evaluator in BNF you will see why recursion is a natural
way to program it.
OTOH, you can do it with "Operator Precedence Grammar" (look it up!), which
might lead to a slightly simpler program.
Once you have done the reading part of your HW, you can tackle the
programming part. I suggest you look into FINITE STATE MACHINES because
that is the easiest way to program pattern-recognition subroutines.
Test the program in bite-sized pieces, i.e. make sure the parser part can
recognize the parts of your formula (terms, factors, operators, functions,
constants, variables, arrays, whatever). Only after that is working should
you decide what to do with the pieces. It would be a good idea to include
diagnostic code while you construct the program--for example something that
will display the current state of the parse tree (if you decide on a tree) or
the expression stack (if you use that), as you decompose the input into
its parts.
If you run into difficulties with C, the folks in this group will help you out,
as I can attest from personal experience. But they really have little interest
in doing your HW for you.
--
Julian V. Noble
Professor Emeritus of Physics
jv*@lessspamfor mother.virginia .edu
^^^^^^^^^^^^^^^ ^^^
http://galileo.phys.virginia.edu/~jvn/
"As democracy is perfected, the office of president represents, more and
more closely, the inner soul of the people. On some great and glorious
day the plain folks of the land will reach their heart's desire at last
and the White House will be adorned by a downright moron."
--- H. L. Mencken (1880 - 1956)