題目描述
對于一元二次方程ax^2 + bx + c = 0,解可以分為很多情況。
若該方程有兩個不相等實根,首先輸出1,換行,然后從小到大輸出兩個實根,兩個根以空格分隔,換行;
若該方程有兩個相等實根,首先輸出2,換行,然后輸出這個實根,換行;
若該方程有一對共軛復根,輸出3,換行;
若該方程無解,輸出4,換行;
若該方程有無窮個解,輸出5,換行;
若該方程只有一個根,首先輸出6,換行,然后輸出這個根,換行;
要求使用c++ class編寫程序??梢詣?chuàng)建如下class
include <iostream>
include <cmath>
include <iomanip>
using namespace std;
class Equation{
private:
int _a, _b, _c;
public:
Equation(int a, int b, int c){
}
void solve(){
}
};
int main(){
int a, b, c;
cin >> a >> b >> c;
Equation tmp(a, b, c);
tmp.solve();
}輸入描述
該一元二次方程的系數(shù)a,b,c,且-100=<a,b,c<=100
輸出描述
解的情況。輸出解的時候保留兩位小數(shù)。
樣例輸入
1 4 3樣例輸出
1
-3.00 -1.00注釋
輸出使用了iomanip庫,比如要輸出a并保留兩位小數(shù),請使用語句: cout << fixed << setprecision(2) << a << endl;
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
class Equation {
private:
int _a, _b, _c;
public:
Equation(int a, int b, int c) {
this->_a = a;
this->_b = b;
this->_c = c;
}
void sove() {
if (_a == 0) {
if (_b == 0) {
if (_c != 0) {
cout << 4 << endl;
}
else {
cout << 5 << endl;
}
}
else {
cout << 6 << endl;
double value = (double)_c / -_b;
cout << fixed << setprecision(2) << value << endl;
}
return;
}
int k = _b * _b - 4 * _a * _c;
double x1, x2;
if (k > 0) {
x1 = (double)(-_b + sqrt(_b * _b - 4 * _a * _c)) / 2 * _a;
x2 = (double)(-_b - sqrt(_b * _b - 4 * _a * _c)) / 2 * _a;
cout << 1 << endl;
cout << fixed << setprecision(2) << x1 << " " << x2 << endl;
}
else if (k == 0) {
x1 = (double)-_b / 2 / _a;
cout << 1 << endl;
cout << fixed << setprecision(2) << x1 << endl;
}
else {
cout << 3 << endl;
}
}
};
int main() {
int a, b, c;
cin >> a >> b >> c;
Equation tmp(a, b, c);
tmp.sove();
return 0;
}