计算二次方程根
Posted flxx
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了计算二次方程根相关的知识,希望对你有一定的参考价值。
#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;
}
以上是关于计算二次方程根的主要内容,如果未能解决你的问题,请参考以下文章