题
我试图写在C ++函数,使用二次方程为X解决。这是我已初步编写的,这似乎只要没有复数的答案,工作:
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,I得到的溶液3,-2正确
我的问题是如何将占到复数....例如,给出的等式:
X ^ 2 + 2×+ 5
手工解决,我会得到-1 + 2I,-1 - 2I
好了,我想2个问题,我可以写上面的更好,也让它占了复数?
感谢您的帮助!
解决方案
像这样将工作:
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)。看起来更漂亮与提升!
编辑:固定增量的东西,并增加了简并情况下,像α= 0的检查。不眠之夜FTL!
其他提示
这是重要的说明这一切。在这些反应,并在原来的问题中示出的解决方案不是鲁棒的。
在公知的解决方案的( - B + - SQRT(B ^ 2 - 4AC))/ 2A 已知是在计算非鲁棒时 AC 是非常小司仪至 b ^ 2 ,因为一个被减去两个非常相似的值。这是更好地使用公知的较轻溶液的 2C /。(-b - + SQRT(B ^ 2 -4ac))对于其它根
一个健壮的解决方案可以被计算为:
temp = -0.5 * (b + sign(b) * sqrt(b*b - 4*a*c);
x1 = temp / a;
x2 = c / temp;
在使用符号(b)中的确保我们不减去两个相似值。
有关的OP,如图其他海报修改此为复数。
您或多或少有它,只是检查,看看是否是这样的平方根内的部分为负,然后在不断减少的那单独跟踪。
您可以基本上只使用std::complex<float>
而不是float
获得对复数的支持。
这Blindy切口的想法:
typedef std::complex<double> complex;
using std::pair;
pair<complex> GetResults(double a, double b, double c)
{
double delta=(b*b-4*a*c);
double inv_2a = 1/2/a;
if(delta >= 0) {
double root = sqrt(delta);
return std::make_pair(
complex((-b-root)*inv_2a),
complex((-b+root)*inv_2a);
} else {
double root = sqrt(-delta);
return std::make_pair(
complex(-b*inv_2a, -root*inv_2a)),
complex(-b*inv_2a, +root*inv_2a)));
}
}
我尝试程序,而无需使用“文件math.h”报头和也尝试了不同的逻辑...但我的程序可以只回答具有“X方”的系数作为一个那些二次方程.....并且其中系数“x”的可以被表达为一个加法两个数它们是常数项的因素。 例如。 X方+ 8×16 +; X方+ 7×+ 12; 等等。这里8 = 4 + 4&16 = 4 * 4;在此,x的系数可以被表达为一个加法两个数它们是常数项16的因素... 我自己是不完全满意,但尝试不同的东西,而无需使用求解二次方程的公式。 码是:
#include<iostream.h>
#include<conio.h>
class quadratic
{
int b,c ;
float l,k;
public:
void solution();
};
void quadratic::solution()
{
cout<<"Enter coefficient of x and the constant term of the quadratic eqn where coefficient of x square is one";
cin>>b>>c;
for(l=1;l<b;l++)
{
for(k=1;k<b;k++)
{
if(l+k==b&&l*k==c)
{
cout<<"x="<<-l<<"\t"<<"or"<<"\t"<<"x="<<-k;
cout<<"\n";
}
}
}
}
void main()
{
quadratic a;
clrscr();
a.solution();
getch();
}