C++二次方程输出:-1.#IND
我的代码工作正常: (1, -2, -8),当我输入 a=1 b=0 c=1 时,它给我上面的错误,
这是我的代码:
double x=0,a=0,b=0,c=0,d=0;
complexType solu1;
complexType solu2;
cout << "\n\nEnter values of quadratic a,b,c:";
cin >> a >> b >> c;
double solution1 = (-1.0 * b) + (sqrt((b * b) - (4 * a * c)));
solu1 = solution1 / (2*a);
cout << setprecision(5) << solu1;
double solution2 = (-b) - (sqrt((b*b) - (4 * a * c)));
solu2 = solution2 / (2*a);
cout << setw(5) << setprecision(5) << solu2;
我该如何解决这个问题?
My code works fine with: (1, -2, -8), It gives me the error above when I input a=1 b=0 c=1,
Here is my code:
double x=0,a=0,b=0,c=0,d=0;
complexType solu1;
complexType solu2;
cout << "\n\nEnter values of quadratic a,b,c:";
cin >> a >> b >> c;
double solution1 = (-1.0 * b) + (sqrt((b * b) - (4 * a * c)));
solu1 = solution1 / (2*a);
cout << setprecision(5) << solu1;
double solution2 = (-b) - (sqrt((b*b) - (4 * a * c)));
solu2 = solution2 / (2*a);
cout << setw(5) << setprecision(5) << solu2;
How can I remedy this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您正在尝试找到
x^2 + 1 = 0
的实数解,该解只有虚数解。如果您想求解所有二次方程,那么您需要检查判别式是否为正,以确定解是实数还是复数:
如果您愿意,您可以使用
std::complex
做一些更简洁的事情。You are trying to find a real solution to
x^2 + 1 = 0
, which only has imaginary solutions.If you want to solve all quadratic equations, then you need to check whether the discriminant is positive to determine whether the solutions are real or complex:
You could do something neater with
std::complex
if you want.输入的
sqrt((b*b) - (4 * a * c))
为sqrt(-4)
。根据 http://www.cplusplus.com/reference/clibrary/cmath/sqrt/ ,如果参数为负数,则会发生域错误,将全局变量 errno 设置为值 EDOM。
在这种情况下,我没有看到它返回的内容的定义。不管怎样,这是错误的。我发现您的代码中有
complexType
。如果这是std::complex
的 typedef,那么代码很容易修复。由于
std::sqrt
具有std::complex
的重载。sqrt((b*b) - (4 * a * c))
for your inputs issqrt(-4)
. According to http://www.cplusplus.com/reference/clibrary/cmath/sqrt/,If the argument is negative, a domain error occurs, setting the global variable errno to the value EDOM.
I don't see a definition for what it returns in that case. Either way, that's wrong.I see that you have
complexType
in your code. If that's a typedef ofstd::complex<T>
, then the code is easily fixable.Since
std::sqrt
has an overload forstd::complex<T>
.