//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()的任何其他選擇都沒有達到我的最終答案? INPUT 給我3.1623 然而答案是3.1622 也輸入10 7給我3.1622777它有一個2小數點後第四位。在C++中找到一個數字的平方根
http://stackoverflow.com/questions/19611198/finding-square-root-without-using-sqrt-function – cokceken
的精度的要點是圓確定當t:在這裏,3.1623更接近3.1622777比3.1622更好,所以把它舍入到3是沒有錯的。一個很好的例子是pi,主要用作3.1416,而更精確的給出3.1415926535 ...兩者都是正確的,只不過更精確 – Adalcar
我會嘗試'double t = .. ';第一。 –