Harsh Pathak
Harsh Pathak

Reputation: 85

finding square root of a number in C++

//find square root of a number n till d decimal points
#include<iostream>
#include<iomanip>

using namespace std;
int main(){
   int n;int d;cin>>n>>d;
   double x=n;int i=1;
   while(i<=20){
       float t=(x+n/x)/2;i++;x=t;
   }
   cout<<fixed<<setprecision(d)<<x<<endl;



   }

The algorithm seems correct,but when I think setprecision rounds off my number which I don't want. Any other alternative to setprecision() which doesn't round off my final answer? INPUT 10 4 gives me 3.1623 however answer is 3.1622 Also input 10 7 gives me 3.1622777 which does have a 2 on 4 th decimal place.

Upvotes: 0

Views: 1490

Answers (1)

nishantsingh
nishantsingh

Reputation: 4652

To truncate the value to d decimal places, multiply with 10^d, take floor, and then divide by the same number.

double multiplier = pow(10, d);
double result = floor(t * multiplier) / multiplier;
cout << fixed << setprecision(d) << result << endl;

Upvotes: 2

Related Questions