-1

calculating the square root of a number

#include<iostream>
#include<math.h>

using namespace std;
int main()
{ 
double pmid=0,n,st=0,en,mid=0;
double dif=3;
cin>> n;               // number whose square root is to be found
en=n;                 // end number    
while(dif>.00000001){
mid =(st+en)/2;       //mid number , st = start number 
if (mid*mid>n){       
    en=mid;          // re positioning end number 
}
else {
    st =mid;          // re positioning end number 
}

dif=fabs(pmid-mid);   //difference between previous and present mid values 
pmid=mid;
cout  <<mid<<" "<<dif<< endl;
}
}

output image

the problem in my results and the results in calculator are different I calculated output of the number 10 as 3.16228 and the google calculator calculates it as 3.16227766017 I think my written code rounds off the value and displays it . How can I get the values as shown by calculator.

Caleb
  • 1,143
  • 5
  • 13
Bogorovich
  • 193
  • 2
  • 11

1 Answers1

2

I don't know if there is another solution but I know that this will work:

cout << setprecision(10);

Run this before you print out your double.

You can set the number to whatever you want but cout << 1.22222222222222222222; will still only print out 1.2222222222222223 since you went over the precision limit of the double.

Nicola Uetz
  • 848
  • 1
  • 7
  • 25