首页 > 解决方案 > 在 C++ 中查找立方根的算法

问题描述

我是编程初学者,我有一个问题。如何在不使用 pow() 之类的函数的情况下在 C++ 中生成立方根查找算法。用户输入数字和小数位数。

我的代码:我做的时候不工作

double number;
cout << "Enter number = ";
cin >> number;
int x;
int y = number / 3.;
int i;
cout << "Enter i = ";
cin >> i;
do {
    x = y;
    y = (2. * x + number / (x * x)) / 3.;
} while (abs(x - y) >= i);
 

标签: c++

解决方案


你的算法几乎没问题。您只需要将变量更改为float/ double。这是编辑后的代码:

#include <iomanip>
#include <iostream>
#include <limits>
using namespace std;

int main() {
    double number;
    cout << "Enter number = ";
    cin >> number;
    double x;
    double y = number / 3.;
    double i;
    cout << "Enter i = ";
    cin >> i;
    do {
        x = y;
        y = (2. * x + number / (x * x)) / 3.;
    } while (abs(x - y) >= numeric_limits<double>::epsilon());
    cout << fixed << setprecision(i) << y;
}

样品运行:

Enter number = 10
Enter i = 2
2.15


加起来一点:

正如chux - Reinstate Monica所指出的,abs(x - y) >= numeric_limits<double>::epsilon()这不是检查平等的好条件。您可以通过此线程获取更多知识:浮点和双重比较最有效的方法是什么?

另一个:为什么是“using namespace std;” 被认为是不好的做法?


推荐阅读