C++计算一元二次方程的跟


#include<iostream.h//2-4

#include<math.h>

voidmain()

{double  a,  b, c,  d,  x1, x2,  rpip ;

   cout << "a, b, c = " ;    cin >> a >> b >> c ;

   if ( fabs( a )<= 1e-8)//<= 1e-8表示==0--浮点数的误差判断!!1

        cout << " It is notquadratic." <<endl ;

   else { d = b * b - 4 * a * c ;

             if ( fabs(d ) <= 1e-8 )

                  cout<< "It has two equal real roots: " << -b / ( 2*a )<<endl ;

             else if ( d > 1e-8 )

         { x1 = ( -b + sqrt( d ) ) / ( 2*a ) ;    x2 = ( -b - sqrt(d ) ) / ( 2*a ) ;

            cout <<"It has two distinct realroots: "<endl;

          }

     else  { rp= -b / ( 2*a ) ;   ip= sqrt(-d ) / ( 2*a ) ;

  cout << "It has two complex roots:" <<endl ;

  cout <<rp<< " + " << ip << "i"<<endl ;

  cout <<rp<< " - " << ip << "i"<<endl ;

              }

  }

}



你可能感兴趣的:(C++经典代码)