二次方程的根
Roots of a Quadratic Equation
本文关键字:二次方程 更新时间:2023-10-16
,所以我正在尝试编写可以计算二次方程的根的上图。这就是我想到的。第一个可能性(d> 0(有效,但其他可能性不做。我在代码中找不到错误。请你帮助我好吗?谢谢!
#include <iostream>
#include <cmath>
using namespace std;
int main(){
float a;
float b;
float c;
float x1;
float x2;
float D=b*b-4*a*c;
float realPart;
float imaginaryPart;
cout << "Write a: " << endl;
cin >> a;
cout << "Write b: " << endl;
cin >> b;
cout << "Write c: " << endl;
cin >> c;
//first possibility D > 0
if (D > 0){
x1=(-b+sqrt(D))/(2*a);
x2=(-b-sqrt(D))/(2*a);
cout << "Results are: x1: " << x1 << " and x2 " << x2 << endl;
}
//second possibility D < 0
else if (D < 0){
realPart = -b/(2*a);
imaginaryPart = (sqrt(-D))/(2*a);
cout << "First result: " << realPart << " + " << imaginaryPart << "i"
<<endl;
cout << "Second result: " << realPart << " - " << imaginaryPart << "i"
<< endl;
}
else if (D == 0){
x1=(-b)/(2*a);
cout << "Result is: " << x1 << endl;
}
else
cout << "THERE'S A MISTAKE!" << endl;
return 0;
}
,虽然您可以实现预定
结果的意图D = b * b - 4 * a * c;
a
, b
和 c
是已知的 1 ,这不是您的情况下发生的事情。
在这里要做的最简单的事情是在a
,b
和c
之后计算描述符D
。IE。在您的程序中进一步移动声明。目前,您的程序的行为不确定。
1 一种方法是使用 Actors 。