二次方程计算器的根错误



我想知道是否有人可以帮助我解决这个问题。所以我测试了代码,但它没有显示下面的正确答案x2 + 5x + 6的方程结果

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>

double roots() {
double a, b, c, x1, x2;
cout << "Enter quadratic equation in order (a, b, c): n";
cin >> a >> b >> c;
double discriminant = b * b - 4 * a * c;
x1 = -b + sqrt(discriminant) / 2 * a;
x2 = -b - sqrt(discriminant) / 2 * a;

if (discriminant >= 0 && a > 1) {
cout << "Your quadratic equation is " << a << "x^2 + " << b << " x + " << c << 'n';
cout << "x1 = " << x1 << 'n';
cout << "x2 = " << x2 << 'n';
}
else if (a == 1) {
cout << "Your quadratic equation is " << "x^2 + " << b << " x + " << c << 'n';
cout << "x1 = " << x1 << 'n';
cout << "x2 = " << x2 << 'n';
}
else {
cout << "Negative value returned from (b2 - 4ac), please try again!";
exit(1);
}
}

int main() {
roots();
}

您的公式有误。试试这个

x1 = (-b + sqrt(discriminant)) / (2 * a);
x2 = (-b - sqrt(discriminant)) / (2 * a);

注意这个额外的括号是为了把2*a放在分母上,让它同时除以bsqrt()

您还需要在这样做之前检查discriminant >= 0,因为如果它是负的,则没有根,并且上面的行将失败。

首先,没有使用命名空间std,所以如果您不想使用它,请编写std::court和std::cin。其次,公式是b^2 -4ac所以你需要在b*b周围加上圆括号这样答案就会从-4ac中减去。然后,你不需要写else if对于a==1你可以把它加到上面的条件中作为a>=1,然后写下一个条件,其中判别式是>=0但a==0违反了二次方程条件,你可以写a不能等于0。此外,x1和x2的主要公式是错误的,因为括号应该应用于-b+平方根(判别式)周围,以便答案然后除以(2*a)的乘法。否则,会发生的情况是,第一个根号除以2,然后乘以a,然后加上-b。

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>

double roots() {
double a, b, c, x1, x2;
std::cout << "Enter quadratic equation in order (a, b, c): n";
std::cin >> a >> b >> c;
double discriminant = (b * b)- (4 * a * c);
x1 = (-b + sqrt(discriminant)) / (2 * a);
x2 = (-b - sqrt(discriminant))/ (2 * a);
if (discriminant >= 0 && a >= 1) {
std::cout << "Your quadratic equation is " << a << "x^2 + " << b << " x 
+ " << c << 'n';
std::cout << "x1 = " << x1 << 'n';
std::cout << "x2 = " << x2 << 'n';
}
else if (a==0){
std::cout << "a cannot be zero!";
exit(1);
}
else{
std::cout << "Negative value returned from (b2 - 4ac), please try again!";
exit(1);
}
}
int main() {
roots();
}

最新更新