好的,所以我在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, 2015\n" << 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;
}
答案 0 :(得分:1)
double
不代表复数。
而不是将double
传递给sqrt
:
sqrt(discriminant)
传递complex number以获得复杂的结果:
sqrt(std::complex<double>(discriminant))