2015-09-17 41 views
-3

我無法解決的問題是我如何找到0和1之間的數字的sqrt。之後,我認爲所有的作品。導致此程序崩潰的唯一輸入數字是0(不包括)和1(不包括)之間的數字試圖找到沒有sqrt函數0和1之間的sqrt數字

任何幫助?

#include <iostream> 
#include <cmath> 
#include <cassert> 
#include <stdlib.h> 
#include <cmath> 

using namespace std; 

double squareroot(double x) /* computes the square root of x */ 

{ 
assert(x >= 0); /* make sure x is not negative*/ 
if (x==0) return 0; 

/* the sqrt must be between xhi and xlo */ 
double xhi = x; 
double xlo = 0; 
double guess = x/2; 

/* We stop when guess*guess-x is very small */ 

while (abs(guess*guess-x) > 0.00001) 
    { 
    if (guess*guess > x) xhi = guess; 
    else xlo = guess; 
    guess = (xhi + xlo)/2; 
    } 

return guess; 
} 

/* Test Stub */ 


int main() 
{ 
    double testvalue; 
    cout << "\n Enter a TestValue= " ; 
    cin >> testvalue; 
    cout << endl; 
    double testresult = squareroot(testvalue); 
    cout << "\n Square Root= " << testresult << "\n" ; 
    } 
+1

Stack Overflow是不是你個人的幫助臺。所以我會說沒有! –

+0

如果程序崩潰了,您是否嘗試在調試器中運行它以捕捉崩潰?否則,你是否嘗試在調試器中逐行執行代碼? –

+0

它不會崩潰。我試着調試它。它工作的很好,但在某些時候我錯過了一些東西。這包括0到1之間的數字的sqrt(例如0,4 0,1 0,7) – Marme

回答

3

您的程序,因爲該行的崩潰:

while (abs(guess*guess-x) > 0.00001)

當你有0和1之間的數字,你的算法總是會導致一個大於0.00001導致無限循環。一種解決方法是將算法改爲另一種平方根逼近技術(參見牛頓法,不動點定理,多項式近似技術等)。

提示:嘗試跟蹤你的代碼,看看發生了什麼,即使你需要把它寫在紙上

+0

最基本的問題是最初的假設,即平方根在'xhi'和'xlo'之間。分數不適用。 – Barmar

+0

我能夠解決它只是添加一個簡單的IF。當x在0和1之間時,xhi = 1和xlo = 0,並且該時間內的過程重複該條件。沒有必要改變逼近技術或所有這些東西。 – Marme