c++ - 在 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);
解决方案
你的算法几乎没问题。您只需要将变量更改为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()
这不是检查平等的好条件。您可以通过此线程获取更多知识:浮点和双重比较最有效的方法是什么?
推荐阅读
- javascript - 使用 Javascript 修改 HTML 代码,其中包含一些用于登录表单的 php 变量
- awk - 将百分比添加到制表符分隔文本中的列
- gcc - MathSage 无法编译 _scproxy
- c# - linecast 总是返回 true
- javascript - 如何将对象列表插入 GoJ?
- python - 从循环内部返回是一种好习惯吗
- php - 使用 TTL 向 Ionic 应用程序发送推送通知
- java - 领域对象共享微服务
- ios - MPMusicPlayerController 需要 7 秒才能开始在 Xamarin.IOS (IOS v11.3) 中播放
- android - 使用 pyjnius 绑定 IBinder 和 LocalBinder