求方程ax2 bx c =0的根 用3个函数分别求当: C++编程

2016-06-21 20:20:01  分类: c++程序设计第三版谭浩强课后答案  参与:

  求方程ax2+bx+c=0的根.用三个函数分别求当:b2-4ac大于0、等于0和小于0时的根并输出结果。在主程序中输入a,b,c的值。

以下是此题的【c++源代码】,需要【c源代码】请点击进入
#include <iostream>
#include <math.h>
using namespace std;
float x1,x2,disc,p,q;
int main()
{void greater_than_zero(float,float);
 void equal_to_zero(float,float);
 void smaller_than_zero(float,float);
 float a,b,c;
 cout<<"input a,b,c:";
 cin>>a>>b>>c;
 disc=b*b-4*a*c;
 cout<<"root:"<<endl;
 if (disc>0)
  {
   greater_than_zero(a,b);
   cout<<"x1="<<x1<<",x2="<<x2<<endl;
  }
 else if (disc==0)
  {equal_to_zero(a,b);
   cout<<"x1="<<x1<<",x2="<<x2<<endl;
  }
 else
  {smaller_than_zero(a,b);
   cout<<"x1="<<p<<"+"<<q<<"i"<<endl;
   cout<<"x2="<<p<<"-"<<q<<"i"<<endl;
  }
 return 0;
}

void greater_than_zero(float a,float b)   /* 定义一个函数,用来求disc>0时方程的根 */
 {x1=(-b+sqrt(disc))/(2*a);
  x2=(-b-sqrt(disc))/(2*a);
 }

void equal_to_zero(float a,float b)     /* 定义一个函数,用来求disc=0时方程的根 */
 {
  x1=x2=(-b)/(2*a);
 }

void smaller_than_zero(float a,float b)  /* 定义一个函数,用来求disc<0时方程的根 */
 {
  p=-b/(2*a);
  q=sqrt(-disc)/(2*a);
 }

来源:c++程序设计第三版谭浩强课后答案

本文链接:http://www.wb98.com/cjia/post/cjia_4.2.html


本站文章搜索:

<< 上一篇下一篇 >>

搜索

Tags列表

赞助商链接