【发布时间】:2016-12-15 06:33:37
【问题描述】:
//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;
}
算法似乎是正确的,但是当我认为 setprecision 将我不想要的数字四舍五入时。 setprecision() 的任何其他替代方案都不能完善我的最终答案? 输入 10 4 给我 3.1623 但是答案是 3.1622 还输入 10 7 给我 3.1622777 它确实有一个小数点后 4 位的 2。
【问题讨论】:
-
精度的点是确定t什么时候四舍五入:这里,3.1623比3.1622更接近3.1622777,所以把它四舍五入到3并没有错。一个很好的例子是pi,主要用作3.1416而更高的精度给出 3.1415926535...两者都一样正确,只是更精确
-
我会先试试
double t = ...;。 -
@RSahu 没用
-
@Adalcar 没错,但我仍然希望答案为 3.1622,因为在线法官没有通过答案
标签: c++