求平方根C++

   求平方根,正根.以前都不会.昨天看数学,看到了,写了出来.自己又小优化了一下,很不错.

// squareRoot.cpp -- 2011-08-29-01.04
#include "stdafx.h"
#include 

double squareRoot (double radicand, double precision) ;

int _tmain(int argc, _TCHAR* argv[])
{
	std ::cout << squareRoot(9, 0.000001) << std ::endl ;

	return 0;
}

double squareRoot (double radicand, double precision)
{
	if (radicand > 0)
	{
		double squareRoot = radicand / 10 ;
		while (squareRoot * squareRoot > radicand)
			squareRoot /= 2 ;
		double fakePrecision = 0.1; 
		while (1)
		{
			while ((squareRoot + fakePrecision) * (squareRoot + fakePrecision) <= radicand)
			{
				squareRoot += fakePrecision ;
			}
			if (fakePrecision > precision)
			{
				fakePrecision /= 10 ;
			}
			else
			{
				return squareRoot ;
			}
		}
	}
	else
	{
		std ::cerr << "Radicand must > 0" << std ::endl ;
		return 0 ;
	}
}

你可能感兴趣的:(算法,c++,优化)