C++二次方程。错误的结果
我写这段代码是为了找到二次方程的根。 代码如下:C++二次方程。错误的结果,c++,quadratic,C++,Quadratic,我写这段代码是为了找到二次方程的根。 代码如下: #include <iostream> #include <cmath> using namespace std; int main() { double a,b,c; double x,x2; cout<<"Give a: "; cin>>a; cout<<"Give b: "; cin>>b; cout <&
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double a,b,c;
double x,x2;
cout<<"Give a: ";
cin>>a;
cout<<"Give b: ";
cin>>b;
cout <<"Give c: ";
cin>>c;
if (a==0)
{
if (b==0)
{
if (c==0)
{
cout<<"Solution indeterminable";
return 0;
}
else
{
cout<<"No solution";
return 0;
}
}
else
{
x=-c/b;
cout<<"The only root is x: "<<x;
return 0;
}
}
else
{
double b_sqr=b*b;
if (b_sqr>4*b*c)
{
cout<<"Complex roots: ";
return 0;
}
else if (b_sqr==4*b*c)
{
x=-b/(2*a);
cout<<"The only solution is x: "<<x;
return 0;
}
else
{
x=-b+(sqrt((b*b)-(4*a*c)))/(2*2);
x2=-b-(sqrt((b*b)-(4*a*c)))/(2*2);
cout<<"The first root is x1: "<<x;
cout<<"The first root is x2: "<<x2;
return 0;
}
}
}
无论我键入什么,它要么找到-1的两个根,要么找到-1的一个根。
我无法理解我的逻辑有什么错误。一切似乎都很好
编辑:
在这种情况下,您没有编译器错误,但代码似乎不起作用。当代码100%正确时,就会发生这种情况,但错误不在于代码中语言的语法或语法,而在于代码背后的逻辑
在开始编码之前,您应该确保所使用的参考资料(详细说明了您试图解决的问题的算法解决方案)是正确的
如果没有编译器错误,但程序没有按预期运行,那么应该检查程序的“详细信息”。你的公式正确吗?你确定你使用的方程式正确吗?就像我之前说的,确保你提到的那些确实是正确的
无论如何,这个问题间接地回答了软件开发的一个重要话题。但是对于那些来这里解决二次方程的C++程序的人来说,这里的工作代码是:
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double a,b,c;
double x,x2;
cout<<"Give a: ";
cin>>a;
cout<<"Give b: ";
cin>>b;
cout <<"Give c: ";
cin>>c;
if (a==0)
{
if (b==0)
{
if (c==0)
{
cout<<"Solution indeterminable";
return 0;
}
else
{
cout<<"No solution";
return 0;
}
}
else
{
x=-c/b;
cout<<"The only root is x: "<<x;
return 0;
}
}
else
{
double b_sqr=b*b;
if (b_sqr<4*a*c)
{
cout<<"Complex roots ";
return 0;
}
else if (b_sqr==4*a*c)
{
x=-b/(2*a);
cout<<"The only solution is x: "<<x;
return 0;
}
else
{
x=-b+(sqrt((b*b)-(4*a*c)))/(2*a);
x2=-b-(sqrt((b*b)-(4*a*c)))/(2*a);
cout<<"The first root is x1: "<<x;
cout<<"The second root is x2: "<<x2;
return 0;
}
}
}
以下可能会有所帮助:
“我不明白我的逻辑出了什么问题”你已经试过调试了吗?嗨。要求人们发现代码中的错误并不特别有效。您应该使用调试器或添加打印语句来隔离问题,方法是跟踪程序的进度,并将其与预期发生的情况进行比较。一旦这两个问题出现分歧,你就发现了问题所在。然后,如果必要,你应该构造一个。仔细检查代码-你有几个非常简单但明显的错误。分母中的2*2应该是2*a作为开始;它还应该分割整个表达式,包括b:4*b*c应该是4*a*c。
bool solve_quadratic(double a, double b, double c, double& x1, double& x2)
{
assert(a != 0);
const double delta = b * b - 4 * a * c;
if (delta < 0) {
return false;
}
if (delta == 0) {
x1 = -b / (2 * a);
x2 = x1;
} else {
const double sqrt_delta = sqrt(delta);
x1 = (-b + sqrt_delta) / (2 * a);
x2 = (-b - sqrt_delta) / (2 * a);
}
return true;
}