• 解一元二次方程的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!
    ";
    
        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;
        }
    }
  • 相关阅读:
    iOS截取长图,自定义截取size
    工作
    UITableView适配iOS11
    利用脚本实现build号自动加一
    iOS原生与JS互调
    CSS高级技巧
    伪元素选择器
    CSS设置过渡
    CSS文本属性 二
    css设置圆角矩形
  • 原文地址:https://www.cnblogs.com/runsdeep/p/11163238.html
Copyright © 2020-2023  润新知