c++二次方程代码输出错误

c++ quadratic equation code output error

本文关键字:错误 输出 代码 二次方程 c++      更新时间:2023-10-16

好的,所以我在c++中创建了一个二次方程求解器,似乎不能在虚数上得到正确的输出。实数根很好(例如x= 2和x= 5),但当虚数出来时,奇怪的事情发生了(x = -1.#IND)?有人能帮我弄明白吗?我想让它更像x = 5.287* I。这是我的代码

#include <iostream>
#include <string>
#include <cmath>
#include <complex>
using namespace std;
int main() {
    cout << "Project 4 (QUADRATIC EQUATION)nLong Beach City College nAuthor: Mathias Pettersson nJuly 15, 2015n" << endl;
    cout << "This program will provide solutions for trinomial expressions.nEXAMPLE: A*x^2 + B*x^2 + C = 0" << endl;
    double a, b, c;
    double discriminant;
    //Variable Inputs
    cout << "Enter the value of a: ";
    cin >> a;
    cout << "Enter the value of b: ";
    cin >> b;
    cout << "Enter the value of c: ";
    cin >> c;
    //Computations
    discriminant = (b*b) - (4 * a * c);
    double x1 = (((-b) + sqrt(discriminant)) / (2 * a));
    double x2 = (((-b) - sqrt(discriminant)) / (2 * a));
    //Output
    if (discriminant == 0)
    {
        cout << "The discriminant is ";
        cout << discriminant << endl;
        cout << "The equation has a single root.n";
    }
    else if (discriminant < 0)
    {
        cout << "The discriminant is ";
        cout << discriminant << endl;
        cout << "The equation has two complex roots.n";
        cout << "The roots of the quadratic equation are x = " << x1 << "*i, and" << x2 << "*i" << endl;
    }
    else 
    {
        cout << "The discriminant is ";
        cout << discriminant << endl;
        cout << "The equation has two real roots.n";
    }
    //Final Root Values
    cout << "The roots of the quadratic equation are x = ";
    cout << x1;
    cout << ", ";
    cout << x2 << endl << endl;
    system("PAUSE");
    return 0;
}

double不表示复数。

double传递给sqrt:

sqrt(discriminant)

传递一个复数来得到一个复数结果:

sqrt(std::complex<double>(discriminant))