【问题标题】:Roots of cubic using C and GSL使用 C 和 GSL 的三次方根
【发布时间】:2012-09-09 01:38:31
【问题描述】:

我正在尝试使用 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,因为我想先测试它是否有效。代码可以编译,但运行时崩溃,没有输出。

我做错了什么?

【问题讨论】:

    标签: c gsl


    【解决方案1】:

    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;
    }
    

    【讨论】:

    • 哦,对了……天哪,这太傻了!谢谢,10分钟后接受。 :)
    【解决方案2】:

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

    解决方案:

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

    简而言之:调用者必须获取接收者变量的地址。收件人变量必须存在

    【讨论】:

      【解决方案3】:

      据你所知,我们有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;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-11-10
        • 2013-09-19
        • 1970-01-01
        • 1970-01-01
        • 2012-12-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多