【问题标题】:c function returning nan instead of doublec函数返回nan而不是double
【发布时间】:2013-08-19 19:36:46
【问题描述】:

我们在我的编程课中学习数值方法,向我们介绍的第一个算法是求根的二分法。这是我使用递归实现它的尝试:

#include <math.h>
#include <stdio.h>

#define tolerance 0.00001

double my_function(double z){
    double answer = 5*pow(z,2) + 5*z - 2;

    return answer;
} 

double bisection(double (*fxn)(double),double a, double b){

    double m = ((a+b)/2);

    if (fabs(b-a) < tolerance){
        double root = a;
        printf("value of a is %lf\n",root);
        return a;
    }



    else if (fxn(m) > 0){
        b = m;
    }

    else if (fxn(m) < 0){
        a = m;  
    } 

    bisection(my_function, a, b);
}

int main(){

    double g = 0.01;
    double z = 1;

    double x = bisection(my_function,g,z);
    printf("root is %lf\n",x);  

return 0;
}

这是输出:

value of a is 0.306225
root is nan

根是正确的(稍微偏离,但在容差范围内),但在返回值和打印它之间的某个地方,它以某种方式变成了 NaN。我难住了。我做错了什么?

【问题讨论】:

  • bisection(my_function, a, b); 在这里你应该使用bisection(fxn, a, b)

标签: c methods recursion nan bisection


【解决方案1】:

我的第一个猜测:

在部分

if (fabs(b-a) < tolerance){
    double root = a;
    printf("value of a is %lf\n",root);
    return a;
}

您返回 a 而不是 root。尝试返回 root 看看是否有帮助。

【讨论】:

    【解决方案2】:

    您没有从递归调用中返回。将bisection中的最后一条语句改为

    return bisection(my_function, a, b);
    

    【讨论】:

    • 谢谢!但是你能解释一下为什么这很重要吗?难道我的一份退货单就够了吗?
    • 不,如果你没有在最后一条语句中包含返回值,则不会返回任何内容,因此分配给main 中的x 的值是未定义的。
    猜你喜欢
    • 2017-06-09
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 2012-12-02
    • 2016-04-20
    • 1970-01-01
    • 1970-01-01
    • 2023-02-16
    相关资源
    最近更新 更多