码迷,mamicode.com
首页 > 其他好文 > 详细

计算二次方程根

时间:2016-11-20 19:00:15      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:stream   art   main   tin   ace   names   and   com   roots   

 

#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;
}

计算二次方程根

标签:stream   art   main   tin   ace   names   and   com   roots   

原文地址:http://www.cnblogs.com/faithlocus/p/6082843.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!