/*
Name: Square root calculation
Author: muguangde
Date: 09/10/2014-18:40PM
Description: This is a program to calculate the square root of
input numbers, binary search method is used, comparing to the
system owned sqrt function.
*/
#include <iostream>
#include <cmath>
#include <fstream>
using namespace std;
int main()
{
double num,cand;
int loopNumber;
void calSqrt(double,double &,int &);//declare key function
ofstream outfile;
outfile.open("output.txt");
//Prompt the users
cout<<"Please input the number"<<endl;
cin>>num;
while(num>0) {
calSqrt(num,cand,loopNumber);
outfile<<"The calculated square root of "<<num<<" is: "<<
cand<<", after "<<loopNumber<<" iterations."<<endl;
outfile<<"The build-in function returns the result: "<<sqrt(num)
<<endl;
outfile<<"*********************************************"<<endl;
cout<<"Please input the number"<<endl;
cin>>num;
}
outfile.close();
return 0;
}
//Function to calculate the sqrt and iteration number
void calSqrt(double num,double &cand,int &loopNumber)
{
double high=0.0,low=0.0;
cand=0.0;
loopNumber=0;
if(num<1.0) {
low=num;
high=1.0;
} else {
low=0.0;
high=num;
}
cand=(low+high)/2.0;
while(fabs(cand*cand-num)>0.000001) {
if(cand*cand>num)
high=cand;
else
low=cand;
cand=(low+high)/2.0;
loopNumber++;
}
}
回到主页
回到目录