编程实现一元二次方程的解 ax^2+bx+c=0

#include "stdafx.h" #include <iostream> #include <cmath> using namespace std; int _tmain(int argc, _TCHAR* argv[]) { double a,b,c; double delta; double x1,x2; cout<<"Please input a,b,c:"<<endl; cin>>a>>b>>c; if(cin.fail()) { cout<<"Error:bad input!"; return 1; } delta=b*b-4*a*c; if(delta>0) { cout<<"The Equation has two roots:"<<endl; x1=(-b+sqrt(delta))/(2*a); x2=(-b-sqrt(delta))/(2*a); cout<<"x1="<<x1<<"/n" <<"x2="<<x2<<"/n"; } if(delta==0) { cout<<"The Equation has two equal roots:"<<endl; x1=(-b+sqrt(delta))/(2*a); cout<<"x1=x2="<<x1<<endl; } if(delta<0) { cout<<"The Equation has two virtual roots:"<<endl; cout<<"x1="<<(-b)/(2*a)<<"+"<<sqrt(-delta)/(2*a)<<"i"<<endl; cout<<"x2="<<(-b)/(2*a)<<"-"<<sqrt(-delta)/(2*a)<<"i"<<endl; } system("pause"); return 0; }

 

实现算法:

 

#include "stdafx.h" #include <iostream> #include <cmath> using namespace std; int sgn(int m) { if(m>=0) return 1; else return -1; } int _tmain(int argc, _TCHAR* argv[]) { double a,b,c; double delta; double q; double x1,x2; cout<<"Please input a,b,c:"<<endl; cin>>a>>b>>c; delta=b*b-4*a*c; if(delta>0) { cout<<"The equation has two roots:"<<endl; q=-(b+sgn(b)*sqrt(delta))/2.0; x1=q/a; x2=c/q; cout<<fixed; cout<<"x1="<<x1<<"/n" <<"x2="<<x2<<endl; } if(delta==0) { cout<<"The equation has two equal roots:"<<endl; q=-(b+sgn(b)*sqrt(delta))/2.0; x1=q/a; cout<<"x1=x2="<<x1<<endl; } if(delta<0) { cout<<"Error!"<<endl; return 1; } system("pause"); return 0; }

你可能感兴趣的:(编程,c,算法,System,input,include)