📄 test.cpp
字号:
#include<stdio.h>
#include<math.h>
float f(float Coef[],float x)
{
return float(Coef[0]+Coef[1]*x+Coef[2]*pow(x,2)+Coef[3]*pow(x,3)+Coef[4]*pow(x,4)+Coef[5]*pow(x,5)+Coef[6]*pow(x,6)+Coef[7]*pow(x,7)+Coef[8]*pow(x,8)+Coef[9]*pow(x,9)+Coef[10]*pow(x,10)+Coef[11]*pow(x,11)+Coef[12]*pow(x,12)+Coef[13]*pow(x,13)+Coef[14]*pow(x,14));
//返回多项式的值
}
void GetCoefficient(float Coef[],int °ree)
{
int a;
printf("please input The degree of the polynomial[3,15]:");
scanf("%d",&a);
fflush(stdin);
degree=a;
printf("please input the coefficients of a polynomial:\n");
for(int i=0;i<=degree;i++)//从低阶到高阶输入系数
{
scanf("%f",&Coef[i]);
fflush(stdin);
}
for(i;i<15;i++)//系数为0的
{
Coef[i]=0.0;
}
}
float GetPrecision()
{
float a;
printf("please input Precision:\n");
scanf("%d",&a);
fflush(stdin);
return a;
}
void SetInitialInterval(float Coef[],int degree,float &xlow,float &xup)
{
float a,b;
printf("please input xlow:\n");
scanf("%f",&a);
fflush(stdin);
xlow=a;
printf("please input xup:\n");
scanf("%f",&b);
fflush(stdin);
xup=b;
}
float ApproximateRoot(float Coef[],int degree,float epsilon,float xlow,float xup)
{
float xres=(xlow+xup)/2;
while(fabs(f(Coef,xres))>epsilon)//二分法求根
{
if(f(Coef,xres)*f(Coef,xup)<0)
xlow=xres;
else
xup=xres;
xres=(xlow+xup)/2;
}
return xres;
}
void main() //主函数
{
float Coef[15];
int degree;
float epsilon;
float xres, xlow, xup;
GetCoefficient(Coef,degree);
epsilon=GetPrecision();
SetInitialInterval(Coef,degree,xlow,xup);
xres=ApproximateRoot(Coef,degree,epsilon,xlow,xup);
printf("the result is : %f",xres);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -