该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
#include
#include
float f(float x) /*定义f函数,以实现f(x)=x*x*x+x*x-3*x-3*/
{
float y;
y=((x+1)*x-3.0)*x-3.0;
return y;
}
float g(float x) /*定义g函数,为f函数的导函数*/
{
float y;
y=(3.0*x+2.0)*x-3.0;
return y;
}
float h(float x) /*定义h函数,以实现x*x*x=-x*x+3*x+3*/
{
float y;
y=(3.0-x)*x+3.0;
return y;
}
rootA() /*定义rootA函数,以实现用二分法求近似根*/
{
int i=0;
float x,y,x1=0,x2=0,y1=0,y2=0;
do
{
printf("Input x1=");
scanf("%f",&x1);
printf("Input x2=");
scanf("%f",&x2);
y1=f(x1);
y2=f(x2);
}
while (y1*y2>=0); /*定义变量x1,x2为区间的两端点,同时保证两个端点的函数值相异*/
do
{
x=(x1+x2)/2;
y=f(x);
if(fabs(y)<1e-6)
break;
if(y*y1>0)
{
x1=x;
y1=y;
}
else
x2=x;
i=i+1; /*定义变量i以计算迭代次数*/
}
while (fabs(x2-x1)>=1e-6); /*设定精确度为1e-6*/
printf("The running number is %d\n",i);
printf("A root of equation is %7f\n",x);
}
rootB() /*定义rootB函数,以实现用基本迭代法求近似根*/
{
float x0=0,x1=0,j;
int k=0,N;
printf("Input the divisor:"); /*选定初值*/
scanf("%f",&x0);
printf("Input the number:"); /*输入最大迭代次数*/
scanf("%d",&N);
printf("Input the Precision:"); /*输入精度*/
scanf("%f",&j);
do
{
x1=pow(h(x0),(1.0/3.0)); /*建立迭代格式*/
if(fabs(x1-x0)
{
printf("A root of equation is %7f\n",x1);
break;
}
x0=x1;
k=k+1;
}while (k<=N);
if(k>N)
printf("It is Failure!\n");
if(k<=N)
printf("The running number is %d\n",k);
}
rootC() /*定义rootC函数,以实现用牛顿切线法求近似根*/
{
float x0,x1,j;
int N,k=0;
printf("Input the divisor:");
scanf("%f",&x0);
printf("Input the number:");
scanf("%d",&N);
printf("Input the Precision:");
scanf("%f",&j);
for(k=0;k<=N;k=k+1)
{
if(fabs(g(x0))<=1e-6)
{
printf("It is Singular!\n");
break;
}
else
{
x1=x0-(f(x0)/g(x0)); /*迭代函数*/
if(fabs(x1-x0)
{
printf("A root of equation is %7f\n",x1);
break;
}
x0=x1;
}
}
if(k>N)
printf("It is Failure!\n");
else
printf("The running number is %d\n",k);
}
void main() /*主函数*/
{
int choose;
char yes_no;
printf("Which method do you want to choose?(1,2,3)\n");
printf("1---------ErFenFa\n");
printf("2---------JiBenDieDaiFa\n");
printf("3---------NiuDunQieXianFa\n");
do
{
printf("You choose is ");
scanf("%d",&choose);
switch(choose)
{
case 1: rootA();break;
case 2: rootB();break;
case 3: rootC();break;
case 0: break;
default: printf("It is error!\n");
}
if(choose==0)
break;
printf("Are you want to contain?(Y/N)");
do
{
scanf("%c",&yes_no);
}
while (yes_no!='Y'&&yes_no!='y'&&yes_no!='N'&&yes_no!='n');
}
while (yes_no=='Y'||yes_no=='y');
}