两道C语言程序题目,急!1.请设计程序,用牛顿迭代法求f(x)=cos(x)-x的近似根,要求精确到10-6。 (1)用

1个回答

  • 第一题代码如下,很简单所以没有什么注释:#include

    #include

    float Fl(float x)

    {

    float y;

    y=cos(x)-x;

    return y;

    }

    float newtoon(float x)

    {

    float y;

    y=x-Fl(x)/(-sin(x)-1);

    return y;

    }

    void main()

    {

    float x0,x1;

    printf("Please input x0:n");

    scanf("%f",&x1);

    do

    {

    float z;

    x0=x1;

    x1=newtoon(x0);

    }while(fabs(x1-x0)>=1e-5);

    printf("The root of equation is %fn",x1);

    }纠正一下上面没看清题目,应该是1e-6第二题代码如下:#include

    #include

    double eff(double x)

    {

    double y;

    y=log(x)+pow(x,2);

    for(;y<=1e-4;){

    if(y>0)

    {

    x=(x+1/exp(1))/2;

    eff(x);

    }

    else

    {

    x=(x+1)/2;

    eff(x);

    }

    }

    return y;

    }

    void main()

    {

    double x,z;

    printf("Please input x:n");

    do

    {

    scanf("%lf",&x);

    }while(x<=1/exp(1)||(x>=1));//输入的数字必须在区间内,因为题目中已经指出在这个区间有一个根!

    z=eff(x);

    printf("the root of the equation is:%lfn",z);

    }

    上面的程序我都运行了一下,差不多对了,第二题用double和float其实是一样的,只不过log函数得到的是double型数据,为了使得程序更加精确我擅自修改了下,楼主改回float也可以。