gpt4 book ai didi

C++在没有sqrt函数循环故障的情况下找到平方根

转载 作者:行者123 更新时间:2023-11-30 05:17:07 24 4
gpt4 key购买 nike

所以我把它作为家庭作业。我知道有很多方法可以使此代码更高效、更准确,但这是我的教授希望完成的方式。

我在循环方面遇到了问题。当我求 67 的平方根时,它确实找到了,但它循环了 3 次正确答案。

Enter a value to be square rooted: 
67
33.5
guess = 17.75
guess = 10.7623
guess = 8.49387
guess = 8.19096
guess = 8.18535
guess = 8.18535
guess = 8.18535
The program took 7 guess to find an estimation.

当我尝试求 5 的平方根时,它找到了,但继续无限循环

using namespace std;

int main()
{
double guess2;
double squarenumber;
double guess1;
int numofguess = 0;

cout << "Enter a value to be square rooted: " << endl;
cin >> squarenumber;
guess1 = squarenumber/2;
cout << guess1 << endl;

do
{

guess2 = (guess1 - (((guess1 * guess1) - squarenumber)/(2* guess1)));
guess1 = guess2;

cout << "guess = " << guess2 << endl;

numofguess = numofguess + 1;

} while ((guess2 * guess2) > squarenumber);

cout<< "The program took "<< numofguess <<" guess to find an estimation.";

return 0;
}

最佳答案

我认为您缺少的是适当的退出条件。您的代码被编写为无限循环,直到猜测“完美”。你应该有一个退出条件来检查当前的猜测是否与之前的猜测相同,这显然意味着你不会做得更好。这是我根据您的代码提出的建议:

using namespace std;

int main()
{
double guess2;
double squarenumber;
double guess1;
int numofguess = 0;

cout << "Enter a value to be square rooted: " << endl;
cin >> squarenumber;
guess2 = guess1 = squarenumber/2;
cout << guess1 << endl;

const double epsilon = squarenumber * 1E-6;
do
{
guess1 = guess2;
guess2 = (guess1 - (((guess1 * guess1) - squarenumber)/(2* guess1)));


cout << "guess = " << guess2 << endl;

numofguess = numofguess + 1;

} while ((guess2 * guess2) > squarenumber && fabs(guess2-guess1) > epsilon);

cout<< "The program took "<< numofguess <<" guess to find an estimation.";

return 0;
}

关于C++在没有sqrt函数循环故障的情况下找到平方根,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42262402/

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