- #include
- #include
- using namespace std;
-
- class HJ107 {
- private:
- static double abs(double x) {
- if (x < 0) {return -x;}
- return x;
- }
- public:
- static double getCubeRoot(double c, double err = 1e-5) {
- double x = c;
- while (abs(c-x*x*x) >= err) {
- x = (2*x + c/(x*x)) / 3.0;
- }
- return x;
- }
- };
-
- int main() {
- double c = 0.0;
- cin >> c;
-
- // 精确到0.01, 最后1位再四舍五入
- double ans = HJ107::getCubeRoot(c, 1e-2);
- // 保留1位小数
- if (ans > 0) {
- ans = int(10 * (ans + 0.05))/10.0;
- } else {
- ans = int(10 * (ans - 0.05))/10.0;
- }
-
- // 保留n位小数, setprecision参数传n+1
- cout << setprecision(2) << ans << endl;
- }
y = x ^ (1/3)
x = y ^ 3;
y^3 - x = 0;
f(y) = y^3 - x;
f'(y) = 3 * (y ^ 2);
根据牛顿迭代法:
Xn1 = Xn - f(Xn) / f'(Xn)
yn1 = y - (y^3 - x) / (3 * y ^ 2) = (2*y + x / y^2) / 3
yn1 为n+1项, y 为n项,得出递推关系式
x换成待开立方需要传入的参数c, y换成x, 迭代后yn1 = y, 得到迭代表达式:
x = (2*x + c /(x * x) )/ 3.0
结束 c == x * x * x, x^3 -> c 结果无限接近, 得到循环条件:
abs(c - x * x * x) >= err