求平方根C++

求平方根C++

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

// 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 ;
	}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/119198.html原文链接:https://javaforall.net

(0)
上一篇 2021年11月14日 下午4:00
下一篇 2021年11月14日 下午4:00


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号