解一元二次方程的C++实现

一元二次方程的根的情况分为实根与虚根两种,代码如下

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

float *solve_equ(float, float, float);//a, b, c
int main()
{
    float a, b, c;
    cout << "enter a, b, c : " << endl;
    cin >> a >> b>>c;
    float *p = solve_equ(a, b, c);
    if (*p == 0)
    {
        cout << "x1= " << *(p + 1) << endl;
        cout << "x2= " << *(p + 2) << endl;
    }
    else if (*p = 1)
    {
        cout << "x1= " << *(p + 1) <<"+"<< *(p + 2) << 'i' << endl;
        cout << "x2= " << *(p + 1) << *(p + 3) << 'i' << endl;
    }
    else cout << "False!\n";

    system("pause");
    return 0;
}
float *solve_equ(float a, float b, float c)
{
    float delta = b * b - 4 * a*c;
    float x1, x2, v1, v2, r; //v stands for virtual part; r stands for real part
    float *t;
    if (delta >= 0)
    {
        int flag=0; //to tell the different kinds of solutions;
        x1 = float(-b + sqrt(delta)) / float(2 * a);
        x2 = float((-b - sqrt(delta))) / float((2 * a));
        t = (float *)malloc(sizeof(float) * 3);
        *t = flag;
        *(t+1) = x1;
        *(t+2) = x2;
        return t;
    }
    else
    {
        int flag=1;
        r = float(-b) / float(2 * a);
        v1 = float(sqrt(-delta)) / float(2 * a);
        v2 = -v1;
        t = (float *)malloc(sizeof(float) * 4);
        *t = flag;
        *(t+1) = r;
        *(t+2) = v1;
        *(t+3) = v2;
        return t;
    }
}