c++ - sqrt 函数的伪代码

标签 c++ c++11

我设法让我的 sqrt 函数完美运行,但我要根据给出的伪代码猜测我是否正确编写了这段代码。

伪代码如下:

x = 1
repeat 10 times:  x = (x + n / x) / 2
return x.

我写的代码,

#include <iostream> 
#include <math.h> 
using namespace std; 

double my_sqrt_1(double n) 
{
double x= 1; x<10; ++x;
return (x+n/x)/2; 
} 

最佳答案

不,您的代码没有遵循您的伪代码。例如,您没有在代码中重复任何内容。您需要添加一个循环来执行此操作:

#include <iostream> 
#include <math.h> 
using namespace std; 

double my_sqrt_1(double n) 
{
  double x = 1;
  for(int i = 0; i < 10; ++i) // repeat 10 times
    x = (x+n/x)/2;
  return x; 
} 

让我们分析一下您的代码:

double x = 1;
// Ok, x set to 1


x < 10; 
// This is true, as 1 is less than 10, but it is not used anywhere

++x;
// Increment x - now x == 2

return (x + n / x) / 2 
// return value is always (2 + n / 2) / 2

由于您没有任何循环,函数将始终在第一次“迭代”时退出并返回值 (2 + n/2)/2

关于c++ - sqrt 函数的伪代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18861111/

相关文章:

c++ - std::async 函数串行运行

c++ - 将文件中的信息插入到结构中

c++ - 在 ARToolKit 中检索标记坐标

c++ - GLEW给出了许多错误信息

c++ - 是否有可能有一个非递归的 at_c 实现?

c++ - 我如何返回包装容器的反向适配器?

c++ - 为什么 stringstream >> 在失败时更改目标值?

c++ - 为什么设置CPU亲和性会使线程运行更慢?

c++11 - 对 'rank'的引用不明确

c++ - 使用 constexpr 函数作为模板参数是否有效?