一元三次方程求解c++
时间: 2023-11-24 15:51:46 浏览: 149
一元三次方程的解法(c++)
4星 · 用户满意度95%
以下是一元三次方程求解的C++代码,其中使用了cmath库中的pow()函数和sqrt()函数:
```c++
#include <iostream>
#include <cmath>
using namespace std;
int main() {
double a, b, c, d;
cin >> a >> b >> c >> d;
double p = -b / (3 * a);
double q = p * p * p + (b * c - 3 * a * d) / (6 * a * a);
double r = c / (3 * a);
double delta = q * q + pow(r - p * p, 3);
double x1, x2, x3;
if (delta > 0) {
double u = cbrt(sqrt(delta) - q);
double v = -cbrt(sqrt(delta) + q);
x1 = u + v + p;
x2 = -(u + v) / 2 + p;
x3 = (u - v) * sqrt(3) / 2;
} else if (delta == 0) {
double u = cbrt(q);
x1 = 2 * u + p;
x2 = -u + p;
x3 = -u + p;
} else {
double theta = acos(q / sqrt(-pow(r - p * p, 3)));
x1 = 2 * sqrt(-r + p * p) * cos(theta / 3) + p;
x2 = 2 * sqrt(-r + p * p) * cos((theta + 2 * M_PI) / 3) + p;
x3 = 2 * sqrt(-r + p * p) * cos((theta + 4 * M_PI) / 3) + p;
}
printf("%.2f %.2f %.2f", x1, x2, x3);
return 0;
}
```
阅读全文