C++程式:求解一元二次方程的所有根


一元二次方程的形式為 ax2 + bx + c。一元二次方程的根由以下公式給出:

Quadratic Equation

共有三種情況:

b2 < 4*a*c - 根是非實數,即複數。

b2 = 4*a*c - 根是實數,且兩個根相同。

b2 > 4*a*c - 根是實數,且兩個根不同。

求解一元二次方程根的程式如下所示。

示例

#include<iostream>
#include<cmath>
using namespace std;
int main() {
   int a = 1, b = 2, c = 1;
   float discriminant, realPart, imaginaryPart, x1, x2;
   if (a == 0) {
      cout << "This is not a quadratic equation";
   }else {
      discriminant = b*b - 4*a*c;
      if (discriminant > 0) {
         x1 = (-b + sqrt(discriminant)) / (2*a);
         x2 = (-b - sqrt(discriminant)) / (2*a);
         cout << "Roots are real and different." << endl;
         cout << "Root 1 = " << x1 << endl;
         cout << "Root 2 = " << x2 << endl;
      } else if (discriminant == 0) {
         cout << "Roots are real and same." << endl;
         x1 = (-b + sqrt(discriminant)) / (2*a);
         cout << "Root 1 = Root 2 =" << x1 << endl;
      }else {
         realPart = (float) -b/(2*a);
         imaginaryPart =sqrt(-discriminant)/(2*a);
         cout << "Roots are complex and different." << endl;
         cout << "Root 1 = " << realPart << " + " << imaginaryPart << "i" <<end;
         cout << "Root 2 = " << realPart << " - " << imaginaryPart << "i" <<end;
      }
   }
   return 0;
}

輸出

Roots are real and same.
Root 1 = Root 2 =-1

在上述程式中,首先計算判別式。如果判別式大於0,則兩個根都是實數且不同。

以下程式碼片段演示了這一點。

if (discriminant > 0) {
   x1 = (-b + sqrt(discriminant)) / (2*a);
   x2 = (-b - sqrt(discriminant)) / (2*a);
   cout << "Roots are real and different." << endl;
   cout << "Root 1 = " << x1 << endl;
   cout << "Root 2 = " << x2 << endl;
}

如果判別式等於0,則兩個根都是實數且相同。以下程式碼片段演示了這一點。

else if (discriminant == 0) {
   cout << "Roots are real and same." << endl;
   x1 = (-b + sqrt(discriminant)) / (2*a);
   cout << "Root 1 = Root 2 =" << x1 << endl;
}

如果判別式小於0,則兩個根都是複數且不同。以下程式碼片段演示了這一點。

else {
   realPart = (float) -b/(2*a);
   imaginaryPart =sqrt(-discriminant)/(2*a);
   cout << "Roots are complex and different." << endl;
   cout << "Root 1 = " << realPart << " + " << imaginaryPart << "i" << endl;
   cout << "Root 2 = " << realPart << " - " << imaginaryPart << "i" << endl;
}

更新於:2020年6月24日

8K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告