解3次方程求出多个解c++
时间: 2023-11-11 21:04:12 浏览: 46
要解一个三次方程,可以使用公式法或者牛顿迭代法。以下是使用公式法的示例代码:
```c++
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
double a, b, c, d; // 三次项系数、二次项系数、一次项系数、常数项
cin >> a >> b >> c >> d;
double delta = pow(b, 2) - 3 * a * c; // 判别式
double x1, x2, x3; // 解
if (delta > 0) // 有三个不同的实数根
{
x1 = (-b + sqrt(delta)) / (3 * a);
x2 = (-b - sqrt(delta)) / (3 * a);
x3 = (-b - sqrt(delta)) / (3 * a);
cout << "x1 = " << x1 << endl;
cout << "x2 = " << x2 << endl;
cout << "x3 = " << x3 << endl;
}
else if (delta == 0) // 有一个实数根和一对复数根
{
x1 = -b / (3 * a);
x2 = x3 = (-b + sqrt(delta)) / (3 * a);
cout << "x1 = " << x1 << endl;
cout << "x2 = " << x2 << " + i" << sqrt(3) / 2 << endl;
cout << "x3 = " << x3 << " - i" << sqrt(3) / 2 << endl;
}
else // 有三个不同的复数根
{
double real = -b / (3 * a);
double imag = sqrt(abs(delta)) / (3 * a);
cout << "x1 = " << real << " + i" << imag << endl;
cout << "x2 = " << real << " - i" << imag << endl;
cout << "x3 = " << real << " + i" << 2 * imag << endl;
}
return 0;
}
```
输入格式为 `a b c d`,输出格式为 `x1 = ...`、`x2 = ...`、`x3 = ...`,其中 `...` 表示对应解的值。注意,如果根为复数,则需要用 `i` 表示虚部。
阅读全文