[英]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. 该算法看似正确,但是当我认为setprecision将我不需要的数字四舍五入时。 Any other alternative to setprecision() which doesn't round off my final answer?
setprecision()的其他替代方法不能使我的最终答案满意吗? 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.
输入10 4给我3.1623,但是答案是3.1622,输入10 7也给我3.1622777,它确实在小数点后四位有2。
To truncate the value to d decimal places, multiply with 10^d, take floor, and then divide by the same number. 要将值截断到小数点d位,请乘以10 ^ d,取小数,然后除以相同的数字。
double multiplier = pow(10, d);
double result = floor(t * multiplier) / multiplier;
cout << fixed << setprecision(d) << result << endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.