0
//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.

6
  • stackoverflow.com/questions/19611198/… Commented Dec 15, 2016 at 6:41
  • The point of precision is to determine when t round: here, 3.1623 is closer to 3.1622777 than 3.1622, so it's not wrong to round it to 3. A good example is pi, mostly used as 3.1416 while more precision gives 3.1415926535... both are just as correct, simply more precise Commented Dec 15, 2016 at 6:42
  • I would try double t = ...; first. Commented Dec 15, 2016 at 6:45
  • @RSahu didn't work Commented Dec 15, 2016 at 6:47
  • @Adalcar That's correct,but I still want answer as 3.1622, as answer is not getting passed by online judge Commented Dec 15, 2016 at 6:48

1 Answer 1

2

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;
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks,but isn't there just a one statement function for giving my answer without rounding off?
There might be. You'd have to search. This is the best I could come up with.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.