編寫一個求方程ax^2+bx+c=0的根的程序,用3個函數分別求當b^2-4ac大於零、等於零和小於零時的方程的根。要求從主函數輸入a、b、c的值並輸出結果-簡單


源程序:

#include < iostream>

#include < math.h >

using namespace std;

void equation_1(int a, int b, int c)

{

  double x1, x2, temp;

  temp = b*b - 4 * a * c;

  x1 = (-b + sqrt(temp)) / (2 * a * 1.0);

  x2 = (-b - sqrt(temp)) / (2 * a * 1.0);

  cout << "兩個不相等的實根" << endl;

  cout << "x1 = " << x1 << ", x2 = " << x2 << endl;

}

void equation_2(int a, int b, int c)

{

  double x1, x2, temp;

  temp = b*b - 4 * a * c;

  x1 = (-b + sqrt(temp)) / (2 * a * 1.0);

  x2 = x1;

  cout << "兩個相等的實根" << endl;

  cout << "x1 = " << x1 << ", x2 = " << x2 << endl;

}

void equation_3(int a, int b, int c)

{

  double temp, real1, real2, image1, image2;

  temp = -(b*b - 4 * a * c);

  real1 = -b / (2 * a *1.0);

  real2 = real1;

  image1 = sqrt(temp);

  image2 = -image1;

  cout << "兩個虛根" << endl;

  cout << "x1 = " << real1 << " + " << image1 << "j" << endl;

  cout << "x2 = " << real2 << " + " << image2 << "j" << endl;

}

void main()

{

  int a, b, c;

  double temp;

  cout << "輸入a,b,c 的值" << endl;

  cin >> a >> b >> c;

  cout << "方程為:" << a << "x*x+" << b << "x+" << c << " = 0" << endl;

  temp = b*b - 4 * a * c;

  if (temp > 0)

    equation_1(a, b, c);

  if (temp == 0)

    equation_2(a, b, c);

  if (temp < 0)

    equation_3(a, b, c);

  system("pause");

}

運行結果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM