Reading in Functions
Usenet file owner
usenet at cps3xx.UUCP
Thu Oct 19 12:43:12 AEST 1989
In article <1197 at utkcs2.cs.utk.edu> wozniak at utkux1.utk.edu (Bryon Lape) writes:
>
> How does one write a procedure in C so that the user can type in
>a formula from the keyboard and the programme will graph it? I can
>handle the graphing part, but what I want to be able to do is is have a
>programme that will read in a function and graph the result.
Sounds like you have to write an expression evaluation program.
Then you could do this:
scanf("%s",buffer);
tree=parse(buffer);
for(x=min;x<=max;x+=step) {
y= eval(x,tree);
plot(x,y);
}
You can find out how to turn the expression into a tree in
books about compilers (maybe interpreters too).
Example:
y=x+3*x
Tree:
add
/ \
/ \
x *
/ \
/ \
3 x
Then the eval() function does an postorder left-then right traversal
of tree. This means:
float eval(struct tree)
{
float t1,t2, calc();
t1=eval(tree.left);
t2=eval(tree.right);
val = calc(t1,t2,tree.function); This function
can be a big switch statement
to perfrom the appropriate
function.
return val;
}
If you only have to evaulate once, you could do the computation
while building the tree, instaed of makeing it a second pass.
Joe Porkka porkka at frith.egr.msu.edu
More information about the Comp.lang.c
mailing list