题目描述
建立一个类Equation,表达方程ax2+bx+c=0。类中至少包含以下方法:
1、无参构造(abc默认值为1.0、1.0、0)与有参构造函数,用于初始化a、b、c的值;
2、set方法,用于修改a、b、c的值
3、getRoot方法,求出方程的根。
一元二次方程的求根公式如下:
一元二次方程的求解分三种情况,如下:
输入
输入测试数据的组数t
第一组a、b、c
第二组a、b、c
输出
输出方程的根,结果到小数点后2位
输入样例1
3
2 4 2
2 2 2
2 8 2
输出样例1
x1=x2=-1.00
x1=-0.50+0.87i x2=-0.50-0.87i
x1=-0.27 x2=-3.73
该题比较简单,主要考察类与构造函数的结合应用,按照题目意思写即可
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
#include <iomanip>
#include<cmath>
#include<cstring>
#include<cctype>
#include<queue>
#include<set>
using namespace std;
class equation
{
double x1, x2, a, b, c;
public:
equation();//无参构造
equation(double a, double b, double c);//有参构造
void set(double aa, double bb, double cc);
void getRoot();
};
equation::equation()
{
a = 1.0;
b = 1.0;
c = 0;
}
equation::equation(double a, double b, double c)
{
this->a = a;
this->b = b;
this->c = c;
}
void equation::getRoot()
{
double d = b * b - 4 * a * c;
if (d > 0)
{
x1 = (-b + sqrt(d)) / (2 * a);
x2 = (-b - sqrt(d)) / (2 * a);
cout << "x1=" << fixed << setprecision(2) << x1 << ' ' << "x2=" << x2 << endl;
}
else if (d == 0)
{
x1 = x2 = (-b) / (2 * a);
cout << "x1=x2=" << fixed << setprecision(2) << x1 << endl;
}
else
{
d = -d;
double q = (-b) / (2 * a);
double w = sqrt(d);
cout << "x1=" << fixed << setprecision(2) << q << '+' << w/(2*a) << 'i' << ' ' << "x2=" << q << '-' << w/ (2 * a) << 'i' << endl;
}
}
void equation::set(double aa, double bb, double cc)
{
a = aa;
b = bb;
c = cc;
}
int main()
{
int t;
double a, b, c;
equation ev;
cin >> t;
while (t--)
{
cin >> a >> b >> c;
ev.set(a, b, c);
ev.getRoot();
}
return 0;
}