求平方根C++

本文介绍了一种手动计算平方根的方法,通过不断逼近精确值来获取结果。该方法首先估算一个初始值,然后逐步调整直到满足预设精度。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

// 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 ;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值