问题描述
我正在尝试用C ++写一个函数,该函数使用二次方程式求解X.这是我最初写的,只要答案没有复数,它似乎就可以工作:
I am trying to write a function in C++ that solves for X using the quadratic equation. This is what I have written initially, which seems to work as long as there are no complex numbers for an answer:
float solution1 = (float)(-1.0 * b) + (sqrt((b * b) - (4 * a * c)));
solution1 = solution1 / (2*a);
cout << "Solution 1: " << solution1 << endl;
float solution2 = (float)(-b) - (sqrt((b*b) - (4 * a * c)));
solution2 = solution2 / (2*a);
cout << "Solution 2: " << solution2;
例如,如果我使用等式:x ^ 2-x-6,我将正确地获得解3,-2.
If, for example, I use the equation: x^2 - x - 6, I get the solution 3, -2 correctly.
我的问题是如何计算复数....例如,给定等式:
My question is how would I account for complex numbers....for example, given the equation:
x ^ 2 + 2x + 5
x^2 + 2x + 5
用手解决,我会得到-1 + 2i,-1-2i.
Solving by hand, I would get -1 + 2i, -1 - 2i.
好吧,我猜有两个问题,我可以更好地写上上面的内容,并考虑到复数吗?
Well, I guess two question, can I write the above better and also make it account for the complex number?
感谢您的帮助!
推荐答案
类似的方法会起作用:
struct complex { double r,i; }
struct pair<T> { T p1, p2; }
pair<complex> GetResults(double a, double b, double c)
{
pair<complex> result={0};
if(a<0.000001) // ==0
{
if(b>0.000001) // !=0
result.p1.r=result.p2.r=-c/b;
else
if(c>0.00001) throw exception("no solutions");
return result;
}
double delta=b*b-4*a*c;
if(delta>=0)
{
result.p1.r=(-b-sqrt(delta))/2/a;
result.p2.r=(-b+sqrt(delta))/2/a;
}
else
{
result.p1.r=result.p2.r=-b/2/a;
result.p1.i=sqrt(-delta)/2/a;
result.p2.i=-sqrt(-delta)/2/a;
}
return result;
}
这样,您就可以以相似的方式获得真实和复杂结果的结果(实际结果只是将虚部设置为0).看起来会更漂亮!
That way you get the results in a similar way for both real and complex results (the real results just have the imaginary part set to 0). Would look even prettier with boost!
edit:修复了delta的问题,并添加了对退化案例(如a = 0)的检查.失眠的夜晚!
edit: fixed for the delta thing and added a check for degenerate cases like a=0. Sleepless night ftl!
这篇关于用C ++求解二次方程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!