我发现了不使用sqrt函数找出平方根的算法,然后尝试进入编程.我最终使用C++中的这个工作代码
#include <iostream>
using namespace std;
double SqrtNumber(double num)
{
double lower_bound=0;
double upper_bound=num;
double temp=0; /* ek edited this line */
int nCount = 50;
while(nCount != 0)
{
temp=(lower_bound+upper_bound)/2;
if(temp*temp==num)
{
return temp;
}
else if(temp*temp > num)
{
upper_bound = temp;
}
else
{
lower_bound = temp;
}
nCount--;
}
return temp;
}
int main()
{
double num;
cout<<"Enter the number\n";
cin>>num;
if(num < 0)
{
cout<<"Error: Negative number!";
return 0;
}
cout<<"Square roots are: +"<<sqrtnum(num) and …Run Code Online (Sandbox Code Playgroud) 试图使用二进制搜索计算出数字的平方根,但是我的实现不起作用,我不知道为什么 - 任何帮助表示赞赏,谢谢
继承我的代码.'end'是我希望平方根的数字的值
while(start <= end) {
float mid = ((start + end) / 2);
printf("\nhalving mid");
if(mid * mid == end){
sqrt = mid;
printf("\nsqrt = %d", sqrt);
}
if(mid * mid < end){
start = mid + 1;
sqrt = mid;
printf("\nsqrt: %d", sqrt);
}
else{
start = mid - 1;
}
}
Run Code Online (Sandbox Code Playgroud) 我正在努力完成一个数学问题,它使用Newton的猜测和检查方法来近似数字的平方根.用户应该输入一个数字,该数字的初始猜测,以及他们想要在返回之前检查他们的答案的次数.为了让事情变得更容易并且了解Python(我几个月前才开始学习这门语言),我把它分解成了许多小函数; 但现在的问题是,我无法调用每个函数并传递数字.
这是我的代码,有帮助的注释(每个函数按使用顺序):
# This program approximates the square root of a number (entered by the user)
# using Newton's method (guess-and-check). I started with one long function,
# but after research, have attempted to apply smaller functions on top of each
# other.
# * NEED TO: call functions properly; implement a counting loop so the
# goodGuess function can only be accessed the certain # of times the user
# specifies. Even if the - .001 range isn't …Run Code Online (Sandbox Code Playgroud)