【发布时间】:2015-08-21 12:01:04
【问题描述】:
我正在创建一个函数,该函数返回一个函数的导数,该函数表示为一棵树
/ + \
* ^
/ \ / \
x 5 3.14 x
具有以下形式的节点
typedef struct node
{
char * fx; // function
struct node * gx; // left-hand side
char * op; // operator
struct node * hx; // right-hand side
} node;
如果一个节点没有子节点,例如x, 5, 3.14 在上面的例子中,那么它的op, gx 和hx 是NULL,否则它的fx 是NULL。
我计算导数的函数看起来像
char * deriveFromTree ( node * rt )
{
char * buff = malloc(100*sizeof(char));
int curBuffIdx = 0;
if (rt->op) // if rt is of the form rt = gx op hx
{
char * dgdx = deriveFromTree(rt->gx); // g'(x)
char * dhdx = deriveFromTree(rt->hx); // h'(x)
char thisop = *rt->op;
if (thisop == '+' || thisop == '-')
{
// ... want to do equivalent of
// buff = dgdx + thisop + dhdx
}
else if (thisop == '*')
{
// ...
}
else if (thisop == '/')
{
// ...
}
else if (thisop == '^')
{
// ...
}
}
else // rt is a base expression -- x or a constant
{
buff[curBuffIdx] = strcmp(rt->fx, 'x') ? '1': '0';
}
buff[++curBuffIdx] = '\0';
return buff;
}
但我在所有字符串添加上都被绊倒了。如果已经有一种紧凑的方法,我可以从头开始创建一个字符串加法器
// ... want to do equivalent of
// buff = dgdx + thisop + dhdx
那么我想使用那个工具。
【问题讨论】:
-
C 使用的唯一“工具”是编译器。否则,您可能会看一下您显然已经在使用的标准字符串库。另外:什么是“字符串添加”?
-
strcat....或者我误解了你的问题 -
通常,“字符串添加”被解释为连接。更准确地说你想做的是“浮点加法,其中数字以十进制表示形式存储在字符串中”?
-
我的个人偏好取决于可用的功能。如果我有动态分配内存功能(
malloc),我将使用动态字符串库,类似于 C++ 自己的std::string类型,这将允许我根据需要增长字符串。否则,我将使用功能类似于非标准 C 函数strlcat的东西,它将截断标记为错误,因为允许信息丢失绝不是一个好主意。
标签: c string algorithm data-structures tree