题目,
image.png
这个题目其实是在有理数范围内和无理数范围内分别计算求根公式的策略。
对于有理数,不支持复数,那么如果求根公式返回负数,就返回 complex<double>(nan, nan)。
如果是无理数,支持复数,那么如果求根公式返回正数,就返回 complex<double>(res, 0)。
如果是无理数,支持复数,并且求根公式返回负数,就返回complex<double>(r, i)。
代码如下,
#include <iostream>
#include <vector>
#include <complex>
#include <tuple>
#include <math.h>
using namespace std;
struct DiscriminantStrategy
{
virtual double calculate_discriminant(double a, double b, double c) = 0;
};
struct OrdinaryDiscriminantStrategy : DiscriminantStrategy
{
double calculate_discriminant(double a, double b, double c) {
return b*b - 4*a*c;
}
};
struct RealDiscriminantStrategy : DiscriminantStrategy
{
double calculate_discriminant(double a, double b, double c) {
int value = b*b - 4*a*c;
if(value < 0) {
return sqrt((double)-1);
}
return value;
}
};
class QuadraticEquationSolver
{
DiscriminantStrategy& strategy;
public:
QuadraticEquationSolver(DiscriminantStrategy &strategy) : strategy(strategy) {}
tuple<complex<double>, complex<double>> solve(double a, double b, double c)
{
auto res = strategy.calculate_discriminant(a, b, c);
if(isnan(res)) {
return {complex<double>(res, res), complex<double>(res, res)};
}
if(res > 0) {
auto x1 = -b/(2*a) + sqrt(res)/(2*a);
auto x2 = -b/(2*a) - sqrt(res)/(2*a);
return {complex<double>(x1, 0), complex<double>(x2, 0)};
}
auto r = -b/(2*a);
auto i = sqrt(-res)/(2*a);
return {complex<double>(r, i), complex<double>(r, -i)};
}
};
网友评论