使用C和GSL的立方根

时间:2012-09-16 17:31:06

标签: c gsl

我正在尝试使用GSL编写一个C程序,按照此处的说明查找三次方程的根:http://www.gnu.org/software/gsl/manual/html_node/Cubic-Equations.html。这就是我想出的:

#include <stdio.h>
#include <gsl/gsl_poly.h>

double *x0,*x1,*x2;
int roots;

int
main (void)
{
    roots = gsl_poly_solve_cubic(0,0,0,x0,x1,x2);

    printf( " %d ", roots);

    return 0;
}

参数是0,0,0,因为我想先测试它是否有效。代码编译但在运行时,它崩溃而没有输出。

我做错了什么?

3 个答案:

答案 0 :(得分:2)

x0,x1和x2只是悬空指针 - 将代码更改为:

double x0,x1,x2;
int roots;

int
main (void)
{
    roots = gsl_poly_solve_cubic(0,0,0,&x0,&x1,&x2);

    printf( " %d ", roots);

    return 0;
}

答案 1 :(得分:2)

你误解了C中如何实现引用语义。请read this answer我刚刚写了完全相同的主题。

<强>解决方案:

double x0, x1, x2;

int roots = gsl_poly_solve_cubic(0, 0, 0, &x0, &x1, &x2);

Nutshell:调用者必须获取收件人变量的地址。收件人变量必须存在

答案 2 :(得分:1)

根据你的说法,我们有gsl_poly_solve_cubic (double a, double b, double c, double * x0, double * x1, double * x2)。你声明3个双指针而不分配任何内存......这将导致段错误 尝试声明双变量并传递它们的地址:

#include <stdio.h>
#include <gsl/gsl_poly.h>


double x0,x1,x2;
int roots;

int
main (void)
{
    roots = gsl_poly_solve_cubic(0,0,0,&x0,&x1,&x2);

    printf( " %d ", roots);

    return 0;
}