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

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

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

相关文章:

  • 2021-05-26
  • 2021-07-15
  • 2021-12-22
  • 2021-10-23
  • 2021-07-02
  • 2022-03-05
  • 2021-06-25
  • 2022-12-23
猜你喜欢
  • 2022-12-23
  • 2021-11-02
  • 2022-12-23
  • 2021-09-29
  • 2021-08-22
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案