有如下结构体的数据
typedef struct tagdata
{
double a;
double b;
double c;
double d;
}data;
有数组数据
data x[1000];
有公式
y = (x.a + x.b + x.c + x.d + 100) / 4
其中数据对应关系为
y[n] = (x[n - 1].a + x[n - 2].b + x[n].c + x[n].d + 100) / 4 (n >= 2)
现在通过构造表达式二叉树完成计算。
定义二叉树节点结构体
typedef struct tagbintree
{
char op;
char level;
double fvalue;
int structindex; /* 用于在计算中识别结构体成员 */
struct tagbintree *lchild;
struct tagbintree *rchild;
}bintree;
添加一个函数 preoffset 处理表达式中数据的坐标变化
double preoffset(data *p, int offset, int structindex)
{
if (structindex == 1)
return (p - offset)->a;
if (structindex == 2)
return (p - offset)->b;
if (structindex == 3)
return (p - offset)->c;
return (p - offset)->d;
}
现在将要计算的表达式做一下变换
y = (preoffset(a, 1) + preoffset(b, 2) + c + d + 100) / 4
原有的计算节点值的函数 double caltree(const bintree *node) 修改成为double caltree(const bintree *node, data *p) ,通过参数p引入数据数组x,完成计算。
表达式树的构造过程没有多大变化,只要将表达式中变量识别之后记录在节点中,最后计算时通过循环以表达式树计算数组x每个元素将结果放进数组y当中。
可以以此来实现由数据绘制函数图像的功能。
在原有的程序基础上做修改很容易的,完整代码就不再写了。

2315

被折叠的 条评论
为什么被折叠?



