2017-08-05 59 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