c++结构体解一元二次方程
时间: 2023-09-21 14:11:01 浏览: 169
C++解一元二次方程
以下是一个简单的 C++ 程序,可以用结构体来解一元二次方程:
```c++
#include <iostream>
#include <cmath>
using namespace std;
struct QuadraticEquation {
double a, b, c;
};
int main() {
QuadraticEquation eq;
cout << "Enter the coefficients of the quadratic equation (ax^2 + bx + c = 0):" << endl;
cout << "a = "; cin >> eq.a;
cout << "b = "; cin >> eq.b;
cout << "c = "; cin >> eq.c;
double delta = eq.b * eq.b - 4 * eq.a * eq.c;
if (delta > 0) {
double x1 = (-eq.b + sqrt(delta)) / (2 * eq.a);
double x2 = (-eq.b - sqrt(delta)) / (2 * eq.a);
cout << "The equation has two real roots: x1 = " << x1 << ", x2 = " << x2 << endl;
} else if (delta == 0) {
double x = -eq.b / (2 * eq.a);
cout << "The equation has one real root: x = " << x << endl;
} else {
double realPart = -eq.b / (2 * eq.a);
double imagPart = sqrt(-delta) / (2 * eq.a);
cout << "The equation has two complex roots: x1 = " << realPart << " + " << imagPart << "i, x2 = " << realPart << " - " << imagPart << "i" << endl;
}
return 0;
}
```
该程序使用 QuadraticEquation 结构体存储方程的系数,然后计算方程的根(如果有)。如果 delta 大于 0,则方程有两个实数根;如果 delta 等于 0,则方程有一个实数根;否则,方程有两个复数根。
阅读全文