C++通过自定义函数求一元二次方程的根


本文实例讲述了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++程序设计有所帮助。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3