0
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
double bisection(double errorVal, double userNum){
double upper=userNum, lower=0;
double mid=(lower+upper)/2.0;
while(!(fabs(mid*mid-userNum)<=errorVal)){
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 "<<std::setprecision(11)<<bisection(errorVal,userNum)<<". The amount of error is "<<fabs(bisection(errorVal, userNum)-sqrt(userNum))<<"."<<std::endl;
}
这是一个原型程序,我设计用于计算用户输入确定的数字的平方根,使用二分法(我知道有更好的方法,例如Newton-Raphson, CORDIC,但这是给定的任务)。平分法平方根计算的问题
唯一剩下的问题是如下:
当userNum
输入是从0到1的小数,程序档位不管指定的精度是什么,与输入0.1,0.1的明显的例外。这产生0.5的不准确的结果,具有0.266227766一个错误,这是上述的0.1规定的误差容限。
我的主要问题是,为何它没有处理0和1之间的数字?
你userprecision是平方值,然后你把它比作上平方根的错误,这是正常的,他们是不一样的 –
啊,我忘了。现在是个大问题......为什么当我给它从0到1的数字时会出错? –
在这条线: 如果(中间*中间> userNum){ 如果您的值是0和1之间,所述条件应<如平方根>到输入值 –