2006年9月全國等級考試三級c語言上機題庫(二十一)

字號:

題目21(無憂id 53 迭代方法求方程題)
    下列程序prog1.c的功能是:利用以下所示的簡單迭代方法求方程:cos(x)-x=0的一個實根。
    Xn+1=cos(Xn)
    迭代步驟如下:
    (1)取X1初值為0.0;
    (2)X0=X1,把X1的值賦給X0;
    (3)X1=cos(X0),求出一個新的X1;
    (4)若X0-X1的絕對值小于0.000001,執(zhí)行步驟(5),否則執(zhí)行步驟(2);
    (5)所求X1就是方程cos(X)-X=0的一個實根,作為函數(shù)值返回。
    請編寫函數(shù)countValue()實現(xiàn)程序的要求,最后調用函數(shù)writeDat()把結果輸出到文件OUT17.DAT中。
    部分源程序已給出。
    請勿改動主函數(shù)main()和輸出數(shù)據(jù)函數(shù)writeDat()的內容。
    #include
    #include
    #include
    float countValue()
    { double x0,x1;
    x1=0.0;
    do{ x0=x1;
    x1=cos(x0);
    }while(fabs(x0-x1)>=0.000001);
    return x1;
    }
    main()
    {
    clrscr();
    printf("實根=%f\n",countValue());
    printf("%f\n",cos(countValue())-countValue());
    writeDat();
    }
    writeDat()
    {
    FILE *wf;
    wf=fopen("OUT17.DAT","w");
    fprintf(wf,"%f\n",countValue());
    fclose(wf);
    }