Description
Implementing the sqrt function. The square root of a number n, can be approximated by repeated performing a calculation using the following formula:
nextGuess = (lastGuess + n / lastGuess) /2
When nextGuess and lastGuess are almost identical, nextGuess is the approximated square root. The initial guess will be the starting value of lastGuess. If the difference between nextGuess and lastGuess is less than a very small number e (such as 0.0001), you can claim that nextGuess is the approximated square root of n.
Input
The first line is a positive integer t (0<t<=20) for the number of test cases. Each test case contains an double value n (0<=n<=100000) and a double value e (such as 0.001).
Output
For each test case, output the square root of n in one line. You should set the precision to 8 and fixed;
Sample Input
2
4 0.001
2 0.01
Sample Output
2.00000009
1.41421569
作业记录。
这题比较棘手的是你不知道lastguess和nextguess的初始设定是啥。
#include<stdio.h>
#include<math.h>
double cal(double,double);
int main(){
int n;
scanf("%d\n",&n);
double c[n],e[n];
for(int i=0;i<n;i++){
scanf("%lf %lf\n",&c[i],&e[i]);
}
for(int i=0;i<n;i++){
printf("%.8lf\n",cal(c[i],e[i]));
}
return 0;
}
double cal(double c,double e){
double next=1,last=c;
while(fabs(next-last)>=e){
last=next;
next = (last + c / last) /2;
}
return next;
}