牛顿迭代法求平方根、立方根(计算一个数字的平方根、立方根,不使用库函数)

求Y的平方根

公式

在这里插入图片描述

C++代码

#include <iostream>
#include <cmath>
using namespace std;
double getSquareBoot(double Y,double precision)
{
	if (Y == 0) return (double)0;
	double an1 = 0;
	double an = 1;  //起始1
	while (1)  
	{
		
		an1 = (an + Y / an) / 2;  //迭代公式

		if (fabs(an1 - an) < precision)//精度判断 precision可换成固定精度值,注意范围
		////if (fabs(an1 - an) < 0.00001)
		{
			break;
		}
		an = an1; //更新数据
	}
	return an1;

}
int main()
{
	cout << getSquareBoot(10, 0.01)<<endl;
	/*double input,output;

	cin >> input;

	output = getSquareBoot(input, 0.01);

	printf("%.1f", output);*/
	////如果需要自己输入被开方数,使用此注释程序;
	////精度可调,也可以在函数中固定精度使用;
    return 0;
}

结果

立方根

公式

在这里插入图片描述

C++代码

#include <iostream>
#include <cmath>

using namespace std;


double getCubeRoot(double Y)
{
	if (Y == 0) return (double)0;
	double an1 = 0;
	double an = 1;  //起始1
	while (1)
	{

		an1 = (2*an + Y / (an*an)) / 3;  //迭代公式

		if (fabs(an1 - an) < 0.0001)//精度判断
		{
			break;
		}
		an = an1; //更新数据
	}
	return an1;

}
int main()
{
	double input,output;

	cin >> input;

	output = getCubeRoot(input);

	printf("%.1f", output);//小数点后一位输出

    return 0;
}

结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_40932028/article/details/105228522