2017-08-05 60 views
2
#include<iostream> 
#include<cmath> 
using namespace std; 
double bisection(double errorVal, double userNum){ 
    double upper=userNum, lower=0; 
    double mid=(lower+upper)/2.0;; 
    while(mid*mid!=userNum){ 
     double mid=(lower+upper)/2.0; 
     if(mid*mid>userNum){ 
      upper=mid; 
     } else { 
      lower=mid; 
     } 
    } 
    return mid; 
} 

int main(){ 
    double errorVal=0, userNum=0; 
    std::cout<<"Please enter a number (larger than 0) to calculate its square root, and the desired margin of error."<<std::endl; 
    std::cin>>userNum>>errorVal; 
    bisection(errorVal,userNum); 
    std::cout<<"The calculated result is "<<bisection(errorVal,userNum)<<". The error is "<<abs(bisection(errorVal,userNum)-sqrt(userNum))<<"."<<std::endl; 
} 

這是一個程序,我已經寫出了通過平分方法輸入的任意數字的平方根。我必須在這裏做錯事,因爲一旦我輸入兩個輸入參數,我就沒有得到任何輸出,這個過程就會停滯在那裏。使用平分法找出數字的平方根的問題

我也想知道如何正確實施errorVal,以指定允許的誤差範圍。謝謝。

+0

還有一件事我忘了提:'請輸入一個數字(大於0)',你試圖在0和1之間的輸入數字,(0,1)?你可能會發現自己陷入了循環;-) – Stefan

回答

1

錯誤值用於修復在執行浮點操作時發生的任何舍入不準確性。

以下聲明很少會是真的,因此您的循環很可能會持續很長時間。

while(mid*mid==userNum) 

的常用方法計算之後比較兩個浮點數是

fabs(x1-x2) < e //where, fabs retrieves the absolute value, 
       //x1,2 are the numbers to compare 
       //and e is the epsilon chosen. 

所以,固定誤差值,或通常被稱爲ε,將固定環,以及。

double bisection(double errorVal, double userNum){ 
    double upper=userNum, lower=0; 
    double mid=(lower+upper)/2.0; 

    //error val added 
    //** fabs(mid*mid - userNum) < errorVal is true if the numers are "equal" 
    //** and you want to run the loop as long as the are NOT "equal" 
    while(!(fabs(mid*mid - userNum) < errorVal)){ 

     mid=(lower+upper)/2.0; 
     if(mid*mid>userNum){ 
      upper=mid; 
     } else { 
      lower=mid; 
     } 
    } 
    return mid; 
} 

參見: http://www.cplusplus.com/reference/cmath/fabs/

https://randomascii.wordpress.com/2012/02/25/comparing-floating-point-numbers-2012-edition/

+0

感謝您的幫助,解決了這個問題的一部分,但現在程序給我一半的輸入作爲輸出。例如:我輸入50,0.001;該程序給我25和17.9289作爲輸出,當它應該顯示sqrt(50)0.001錯誤。 –

+1

啊,有一個模棱兩可的變量聲明:'double mid'被定義兩次。你應該擺脫這一點。我會編一些代碼。噢,這個詭計是錯的;-) – Stefan