C程问题??

来源:百度知道 编辑:UC知道 时间:2024/06/24 07:46:56
下列程序的功能是:利用以下所示的简单迭代方法求方程:
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,执行步骤(5),否则执行步骤(2)。
(5)所求x1就是方程cos(x)-x=0的一个实根,作为函数值返回。
请编写函数countValue ( )实现程序要求,最后调用函数writeDAT( )把结果输出到文件out.dat中。

我写的程序是:

#include<math.h>
#include<stdio.h>
#include<stdlib.h>
void writeDAT();

float countValue( )
{
float x1=0.0,x0;
do
{
x0=x1;
x1=cos(x0);
}
while ((x0-x1)>=0.000001)||((x0-x1)<=(-0.000001));
return x1;
}

void main( )
{
system("CLS");
printf("实根=%f\n",countValue( ));
printf("%f\n",cos(countValue( ))-countValue( ));
writeDAT( );
}

void writeDAT( )
{
FILE *wf;
wf=fopen("out.dat","w");
fprintf(wf,"%f\n"

#include<math.h>
#include<stdio.h>
#include<stdlib.h>
void writeDAT();

float countValue( )
{
float x1=0.0,x0;
do
{
x0=x1;
x1=(float)cos(x0);
}
while ((x0-x1)>0.000001||((x0-x1)<(-0.000001)));
return x1;
}

void main( )
{
system("CLS");
printf("实根=%f\n",countValue( ));
printf("%f\n",cos(countValue( ))-countValue( ));
writeDAT( );
}

void writeDAT( )
{
FILE *wf;
wf=fopen("out.dat","w");
fprintf(wf,"%f\n",countValue( ));
fclose(wf);
}

warning是因为cos函数返回的是double类型你把它赋值给float的变量
error是因为你的括号打错了

缺少括号
while ( ((x0-x1) >= 0.000001 )||((x0-x1)<=(-0.000001));

cos函数返回的是double型数据,你的x1是float型数据,数据类型不匹配,double转换成float会截断一部分数据,所以报了第一个警告。

error的产生原因是因为while ((x0-x1)>=0.000001)||((x