本文實例講述了C++通過自定義函數求一元二次方程的根。分享給大家供大家參考,具體如下:
/** 作 者: 劉同賓* 完成日期:2012 年 11 月 24 日* 版 本 號:v1.0* 輸入描述:* 問題描述: 求一元二次方程的根。定義函數* 程序輸出:* 問題分析:略* 算法設計:略*/#include<iostream>#include<cmath>using namespace std;double x,x1,x2,t; //定義全局變量void f1(); //函數聲明double f2(double a,double b);void f3(double a,double b,double c);int main(){ double a,b,c; cout<<"請輸入a,b,c的值:"<<endl; cin>>a>>b>>c; t=b*b-4*a*c; if(t==0) //由根的判別式來決定執行哪條分支 { f2(a,b); cout<<"x1=x2="<<x; } else if(t<0) { f1(); } else { f3(a,b,c); cout<<"x1="<<x1<<endl; cout<<"x2="<<x2; } cout<<endl; return 0;}void f1(){ cout<<"此方程無根!"<<endl;}double f2(double a,double b){ x=-b/(2*a); return x;}void f3(double a,double b,double c){ x1=((-b+(sqrt(t)))/(2*a)); x2=((-b-(sqrt(t)))/(2*a));}
運行效果截圖如下:
希望本文所述對大家C++程序設計有所幫助。