1、用C+解决一元二次方程根的问题集锦c+求一元二次方程ax+bx+c=0的根一#include #include #define ESSP 0.00000001 void main() double a,b,c,delta,root1,root2; couta; coutb; coutc; delta=b*b-4*a*c; if(delta-ESSP) coutThis equation has no real root.ESSP) root1=(-b+sqrt(delta)/(2*a); root2=(-b-sqrt(delta)/(2*a); coutThis eqution has two
2、 unequalize roots:root1root2endl; else root1=-b/(2*a); coutThis eqution has two equalize roots:root1endl; 二结构化编程方法: /for two roots #include #include int main() double a,b,c,rp,ip;/方程系数 double x1,x2;/方程的根 double d;/根的判别式 coutabc; if(a=0) cout= 0) if (d=0) x1 = -b / (2*a); cout只有一个实根:x1endl; else x1 =
3、 ( -b + sqrt ( d ) ) / ( 2 * a ); x2 = ( -b - sqrt ( d ) ) / ( 2 * a ); cout有二个实根:x1andx2endl; else rp = -d/(2*a); ip = sqrt ( -d ) /(2*a); x1 = rp + ip ; x2 = rp - ip ; cout有二个虚根:x1iandx2i0) x1=(-b+sqrt(d)/(2*a); x2=(-b-sqrt(d)/(a*a); else if(d=0) x1=x2=(-b)/(2*a); else double rp = -d/(2*a); double
4、 ip = sqrt ( -d ) /(2*a); x1=rp + ip; x2=rp - ip; void FindRoot:Display() if(d0) coutx1=x1nx2=x2endl; else if(d=0) coutx1=x2=x1endl; else coutx1=x1iendl; coutx2=x2iendl; void main() FindRoot obj(1,2,3); obj.Find(); obj.Display(); 三根据要求编写程序。 从键盘输入三个实数a、b、c分别作为一个一元二次方程ax2+bx+c=0 的三个系数。使用系 统给出的平方根函数,编写
5、一段程序,使之求出这个方程的两个根。其中,求=b2-4*a*c 的功能要以函数形式出现。(提示:求根公式,0) x1=(-b)+sqrt(disc); x2=(-b)-sqrt(disc); printf(x1=%.2ftx2=%.2fn,x1,x2); else printf(b-4ac0,该方程没有实根n,x1,x2); #include stdio.h int a8=0; int getResult(int n) if(n=1|n=2) return 1; else return 3*getResult(n-1)-getResult(n-2); void main() int i; a0
6、=1; a1=1; for(i=2;i8;i+) ai=getResult(i+1); for(i=0;i8;i+) printf(a%d = %dn,i+1,ai); 四用C语言编写一个程序,计算一元二次方程的解(x1,x2)。一元二次方程:Ax2+Bx+C=0 (假设A=4,B=6,C=1)按顺序输入a,b,c #include stdio.h #include stdlib.h #include math.h int main() float a,b,c; scanf(%f,&a); scanf(%f,&b); scanf(%f,&c); printf(%fn,(-b+sqrt(b*b-
7、4*a*c)/2/a); printf(%f,(-b-sqrt(b*b-4*a*c)/2/a); system(pause); return 0; ;五解一元二次方程的C+程序 #include #include #include void sqrt1(double,double); void sqrt2(double,double); void printer(double,double); void main() float a,b,c; double x1,x2; cout请输入a,b,c:abc; if(b*b-4*a*c !=0) if(b*b-4*a*c) sqrt1(x1,x2)
8、; else printer(x1,x2); else sqrt2(x1,x2); void sqrt1(double x1,double x2) /b*b-4ac0 float a,b,c; if(a!=0) x1=(-b+sqrt(b*b-4*a*c)/(2*a); x2=(-b-sqrt(b*b-4*a*c)/(2*a); coutx1=x1setw(5)x2=x2endl; else if(b=0) if(c=0) coutx为任意解endl; else cout无解endl; else x1=x2=-c/b; coutx1=x2=x1endl; void sqrt2(double x
9、1,double x2) /b*b-4ac=0 float a,b,c; x1=x2=-b/(2*a); coutx1=x2=x1endl; void printer (double x1,double x2) /b*b-4ac0 float a,b,c; char i=i;/i后面为虚部 x1=(-b/(2*a)+(i*(sqrt(b*b-4*a*c)/(2*a); x2=(-b/(2*a)-(i*(sqrt(b*b-4*a*c)/(2*a); coutx1=x1tx2=x20,有两个不等实根。 (4) b2-4ac0,有两个复根(表示成x+yi,x-yi)。 2编写一个程序,打印下列图形: 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 3. 编写一个函数将一nxn矩阵转置(即aij与aji的值交换),然后编写一main( ) 函数调用它(取n=3)。第1个我记得书上有例题的 第2个: #include int main() for(int i=1;i=5;i+) for(int j=1;j=i;j+
copyright@ 2008-2022 冰豆网网站版权所有
经营许可证编号:鄂ICP备2022015515号-1