所以我把它作爲一項家庭作業。我明白有很多方法可以讓代碼更加高效和準確,但這是我的教授想要完成的方式。C++找到沒有sqrt函數循環毛刺的平方根
我有循環問題。當我問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;
}
,而在調試器中逐行執行代碼? –
嘗試每次通過循環打印'guess2 * guess2'。確保用大量的精確數字打印。 – Barmar
雙精度數據包含6位以上的十進制數字,因此可能不會顯示數字的差異。檢查這篇文章[浮點數學破碎?](http://stackoverflow.com/questions/588004/is-floating-point-math-broken) –