1. 程式人生 > >【學堂線上】 一元二次方程求解

【學堂線上】 一元二次方程求解

題目描述
對於一元二次方程ax^2 + bx + c = 0,解可以分為很多情況。

若該方程有兩個不相等實根,首先輸出1,換行,然後從小到大輸出兩個實根,換行;

若該方程有兩個相等實根,首先輸出2,換行,然後輸出這個這個實根,換行;

若該方程有一對共軛復根,輸出3,換行;

若該方程有無解,輸出4,換行;

若該方程有無窮個解,輸出5,換行;

若該方程只有一個根,首先輸出6,換行,然後輸出這個跟,換行;

要求使用c++ class編寫程式。

#include <iostream>
#include <cmath>//sqrt開平方函式需要用到的標頭檔案
#include<iomanip>//保留小數點後兩位需要的標頭檔案 using namespace std; class Equation{ private: int _a, _b, _c; public: Equation(int a, int b, int c){//建構函式 _a = a; _b = b; _c = c; } void solve();//成員函式 }; void Equation::solve(){//類外實現成員函式 double a = _a, b = _b, c = _c; if (a == 0){ if (b == 0){ if
(c == 0) cout << 5 << endl; else cout << 4 << endl; } else{ cout << 6 << endl; cout << fixed << setprecision(2) << -c / b << endl; /*<< fixed << setprecision(2)表示保留小數點後兩位*/ } } else{ double delta = b*b -
4 * a*c; if (delta > 0){ cout << 1 << endl; double i = (-b + sqrt(b*b - 4 * a*c)) / (2 * a); double j = (-b - sqrt(b*b - 4 * a*c)) / (2 * a); if (i > j){//為了滿足題目條件:結果按從大到小的順序輸出 double temp; temp = i; i = j; j = temp; } cout << fixed << setprecision(2) << i <<" "<< j << endl; } else if (delta = 0){ cout << 2 << endl; cout << fixed << setprecision(2) << -b / (2 * a) << endl; } else cout << 3 << endl; } } int main(){ int a, b, c; cin >> a >> b >> c; Equation tmp(a, b, c); tmp.solve(); return 0; }