c 自定义sqrt算法。

转载自:http://www.examw.com/biancheng/c/194822/

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

#define ACC 0.000000001

double newSqrt(double n)
{
	double low, high, mid, tmp;

	if(n > 1) 
	{
		low = 1;
		high = n;
	}
	else
	{
		low = n;
		high = 1;
	}

	while(low <= high) 
	{
		mid = (low + high) / 2.000;
		tmp = mid*mid;

		if (tmp - n <= ACC && tmp - n >= ACC*(-1))
		{
			return mid;
		}
		else if (tmp > n )
		{
			high = mid;
		}
		else
		{
			low = mid;
		}
	}
	return -1.00;
}

int main(int argc, char *argv[])
{
	printf("Hello, world\n");
	
	double n, res;
    while (1) 
	{
		scanf("%lf", &n);
		printf("%lf\n", n);
		res = newSqrt(n);
		printf("%lf\n", res);
	}
	return 0;
}

  

posted on 2015-07-08 13:56  嘘寒问暖  阅读(471)  评论(0编辑  收藏  举报

导航