gpt4 book ai didi

c++ - 使用二次公式的简单二次方程计算器

转载 作者:行者123 更新时间:2023-12-01 14:09:55 25 4
gpt4 key购买 nike

我想知道是否有人可以帮助我解决这个(初学者)问题。
我正在创建一个非常基本的二次方程计算器。我在下面列出了我的代码和注释(代码片段顶部的那些解释了我必须做什么)。我已经在网上查看了多种解决方案并尝试了自己,但似乎我不断收到不正确的 x1 和 x2 值。如果有人能指导我,我会非常高兴。干杯。

/* 
create program to calculate x for quadratic equation. (a, b and c)
1) create function which prints out roots of quad equation.
2) throw exception if b2 - 4ac is less than 0.
3) call the function from main.
*/

#include <iostream>
#include <cmath>
#include <string>

using namespace std;

double roots() { //return type, function name, parameters and body of function.
double a = 0, b = 0, c = 0, x1, x2;
double discriminant = (b * b) - 4 * a * c;
cout << "Enter roots of quad equation (in order: a, b, c) " << endl;
cin >> a >> b >> c;

if (discriminant >= 0) {

cout << "Your quadratic equation is: " << a << "x squared + " << b << "x + " << c << " = 0 " << endl;
x1 = -b + sqrt(discriminant) / (2 * a);
x2 = -b - sqrt(discriminant) / (2 * a);
cout << "x1 = " << x1 << endl;
cout << "x2 = " << x2 << endl;
}
else {
cout << "Negative value returned from (b2 - 4ac), please try again! " << endl;
exit(1);
}
}

int main() {

cout << "Quadratic Equation Calculator " << endl;
roots();




return 0;
}

最佳答案

这是一个简单的错误。您只是以错误的顺序放置了代码行。这应该解决它:

/* 
create program to calculate x for quadratic equation. (a, b and c)
1) create function which prints out roots of quad equation.
2) throw exception if b2 - 4ac is less than 0.
3) call the function from main.
*/

#include <iostream>
#include <cmath>
#include <string>

using namespace std;

double roots() { //return type, function name, parameters and body of function.
double a = 0, b = 0, c = 0, x1, x2;
cout << "Enter roots of quad equation (in order: a, b, c) " << endl;
cin >> a >> b >> c;
double discriminant = (b * b) - 4 * a * c; // restructed this line

if (discriminant >= 0) {

cout << "Your quadratic equation is: " << a << "x squared + " << b << "x + " << c << " = 0 " << endl;
x1 = -b + sqrt(discriminant) / (2 * a);
x2 = -b - sqrt(discriminant) / (2 * a);
cout << "x1 = " << x1 << endl;
cout << "x2 = " << x2 << endl;
}
else {
cout << "Negative value returned from (b2 - 4ac), please try again! " << endl;
exit(1);
}
}

int main() {

cout << "Quadratic Equation Calculator " << endl;
roots();




return 0;
}

关于c++ - 使用二次公式的简单二次方程计算器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63315747/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com