c++ - 链表中多项式的导数

标签 c++

出于某种原因,当我尝试求导时,它只是求一个项的导数,而不是整个多项式。

struct term{
    double coef;
    unsigned deg;
    struct term * next;
    };

我有一个结构,然后还有一个带有深度复制构造函数和 = 构造函数的 Polynomial 类。 在私有(private)类(class)中,我有一个 term* ptr

这是我的衍生代码

void Polynomial::derivative (Polynomial *p){
    term *x;
    if ( ptr == NULL)
        return ;
    term *temp;
    temp = ptr;
    while (temp != NULL){
       if ( ptr == NULL){
            ptr = new term ;
            x = ptr ;
        }
        else{
            x -> next = new term ;
            x = x -> next ;
        }
        x-> coef = temp -> coef * temp -> deg;
        x-> deg = temp -> deg - 1;
        temp = temp -> next;

    }
    ptr=x;
}

所以当我尝试求导 3x^4 + 3x^4 + 6x^7 + 3x^4 + 3x^4 + 6x^7 + 2x^9 我得到 18x ^8

我查看了代码,不知道为什么它只对最后一项这样做,因为它是一个 while 循环,应该从头开始直到 NULL 并进行导数。

最佳答案

由于这两行,你得到了最后一个词:

在你的其他条件下:

x = x -> next

和你的最终作业:

ptr = x;

因此,这也会泄漏内存,因为您之前分配的所有漂亮术语现在都在以太中。无论如何你都在泄露旧的,所以无论如何这真的需要重新考虑。

我强烈建议,因为你的 Polynomial 类支持完整的复制构造和赋值操作,你从这个创建一个导数多项式,并返回那个。如果调用者想要转换这个,他们可以 poly = poly.derivative(); 自己。

导数生成器示例(相对于转换器)。作为奖励,在生成导数时消除了所有常数项。

Polynomial Polynomial::derivative() const
{
    Polynomial poly;

    const term *p = ptr;
    while (p)
    {
        if (p->deg != 0) // skip constant terms 
        {
            // add term to poly here (whatever your method is called)
            poly.addTerm(p->coef * p->deg, p->deg-1);
        }
        p = p->next;
    }
    return poly;
}

这允许这种生成:(注意 p1 未被 derivative() 更改):

Polynomial p1;
... populate p1...
Polynomial p2prime = p1.derivative();

对于真正令人愉快的事情:

Polynomial p1;
... populate p1...
Polynomial p2prime2 = p1.derivative().derivative();

无论如何,我希望这是有道理的。

关于c++ - 链表中多项式的导数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13615375/

相关文章:

c++ - Skia SkCanvas不能用SkBitmap构造

c++ - 查找数组中一组数字的起点和终点

c++ - QtCreator IDE不能同时使用IntelliSense和 "auto"类型推断吗?

c++ - 从可调用可变参数元组中的函数结果创建元组

c++ - 平铺 + OpenGL 纹理翻转

c++ - 常数乘法的奇怪值

c++ - 深拷贝和动态转换 unique_ptr

C++ 未找到 << 运算符,它采用右手操作数

C++ 多线程 : terminate after throwing an instance of 'std::length_error'

c++ - 检查二维网格的元素是否与另一个元素共享对角线、水平线或垂直线