- 一元三次方程求解
- 2016-09-01 18:52:55 @
#include<stdio.h>
#include<stdlib.h>
#include<math.h>
double a,b,c,d;
double f(double s)
{
return a*s*s*s+b*s*s+c*s+d;
}
int main()
{
int x,x0,biao=3;
double m,i,j;
scanf("%lf %lf %lf %lf",&a,&b,&c,&d);
for(x=-100;x<101;x++)
{
x0=x+1;
i=(double)x;
j=(double)(x+1);
if(f(i)==0)
{
printf("%.2lf ",i);
biao--;
}
else
{
if(f(i)*f(j)<0)
while(1)
{
m=(i+j)/2;
if(abs(i-j)<=0.001)
{
printf("%.2lf ",m);
biao--;
break;
}
if(f(m)==0)
{
printf("%.2lf ",m);
biao--;
break;
}
if(f(i)*f(m)<0) j=m;
if(f(j)*f(m)<0) i=m;
if(abs(i-j)<=0.001)
{
printf("%.2lf ",m);
biao--;
break;
}
}
}
if(biao==0) break;
}
return 0;
}
6 条评论
-
方晨羽 LV 9 @ 2016-09-01 19:16:19
典型二分
-
2016-09-01 19:15:57@
#include<iostream> #include<cstdio> using namespace std; double a,b,c,d; int top=1; double x[5]={0}; double fun(double s){ return a*s*s*s+b*s*s+c*s+d; } void search(double s,double t){ if((t-s)<0.001){ x[top++]=s; return; } if(fun(s)*fun(t)<0){ double mid=(s+t)/2; if(fun(s)*fun(mid)==0){ x[top++]=mid; return; } else if(fun(s)*fun(mid)<0){ search(s,mid); } else if(fun(mid)*fun(t)<0){ search(mid,t); } } } int main(){ int i; cin>>a>>b>>c>>d; for(i=-100;i<=100;i++){ if(top==4) break; if(fun(i)*fun(i+1)<0){ if(fun(i)*fun(i+0.5)<0){ search(i,i+0.5); } else if(fun(i+0.5)*fun(i+1)<0){ search(i+0.5,i+1); } } else if(fun(i)*fun(i+1)==0){ if(fun(i)==0){ x[top++]=i; } } } for(i=1;i<=3;i++){ printf("%.2f ",x[i]); } return 0; }
-
2016-09-01 19:14:40@
这是pascal的,还有C++的,别着急
-
2016-09-01 19:14:15@
const min=-100.0; max=100.0; eps=0.001; var num:longint; a,b,c,d,i:double; function f(x:double):double; begin exit(a*x*x*x+b*x*x+c*x+d); end; function isroot(x:double):boolean; begin exit(abs(f(x))<eps); end; begin readln(a,b,c,d); num:=0; i:=min; repeat if isroot(i) then begin write(i:0:2,' '); num:=num+1; i:=i+1; end else i:=i+eps; until (num>=3) or (i>max); writeln; end.
-
2016-09-01 19:13:22@
我等会儿发上来
-
2016-09-01 19:13:05@
喔,看看我代码。
- 1