首页 > 代码库 > 计算二次方程根

计算二次方程根

 

#include <cmath>
#include <iostream>
using namespace std;

template<typename T>
bool OutputRoots(const T& a,const T& b,const T& c)
{
    if(0 == a)
    {
        cout << "被除数不能为0!" << endl;
        return -1;
    }
    T d = b*b -4*a*c;
    if(d > 0)   // 两个实根
    {
        float sqrtd = sqrt(d);
        cout << "There are two real roots "
             << (-b+sqrtd)/(2*a) << " and "
             << (-b-sqrtd)/(2*a) << endl;
    }
    else if(d == 0) // 两个根据相等
    {
        cout << "There is only one distinct root "
             << -b/(2*a) << endl;
    }
    else // 两个复根
    {
        cout << "The roots are complex " << endl
             << "The real part is "
             << -b/(2*a) << endl
             << "The imaginary part is "
             << sqrt(-d)/(2*a) << endl;
    }
    return true;
}

int main()
{
    OutputRoots(0,-5,6);
    return 0;
}

计算二次方程根