[Functions]D. Liang 5.23 Approximating the square root

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;	
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值