gpt4 book ai didi

c++ - sqrt 函数的伪代码

转载 作者:太空狗 更新时间:2023-10-29 23:36:14 27 4
gpt4 key购买 nike

我设法让我的 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/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com