2009/10/15

[ C/C++ ] Quadratic by C++

使用 C++ 解一元二次方程式

// quadratic.cpp
//
// This program solves a quadratic equation in standard form.
// ax^2 + bx + c = 0
//
// Console-based
// Retruns real as well as comples roots.
// Author Jim.lin 2009

#include <iostream>
#include <stdio.h>
#include <math.h>

using namespace std;

double a,b,c;
double x1,x2;
double i;

// main function
int main()
{
    cout<<"Please Input Number a,b,c:\n";
    cin>>a>>b>>c;
    i=sqrt(b*b-4*a*c);
    if(i<0)
        cout<<"This is imaginary roots";
    else if(i==0)
    {
        x1=-b/(2*a);
        cout<<"The quadratic equation has one root" << x1 << endl;
    }
    else
    {
        x1=(-b+i)/(2*a);
        x2=(-b-i)/(2*a);
        cout<<"The quadratic equation has two roots" << endl;
        cout<<"x1=" << x1 << "  x2=" << x2 << endl;
    }
}
Best Code : http://jblanco_60.tripod.com/c_pp_quadratic.html

0 意見: