欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

用牛顿迭代法,自己实现sqrt(和abs)函数功能

程序员文章站 2022-06-03 12:21:52
...
#include<stdio.h>
int main()
{
	double abs(double num);
	double sqrt(double numb);
	double x,y;
	printf("请输入要开方的数(必须为正数!):");
	scanf("%lf",&x);
	while(x<=0)
	{
		printf("非法输入!请重新输入:");
		scanf("%lf",&x);	
	}
	y=sqrt(x);
	printf("\n结果为:sqrt(%5.4lf)=%17.16lf\n",x,y);
	return 0;
} 

double abs(double num)
{
	double ans;
	if(num<0) ans=-num;
	else ans=num;
	return(ans);
}

double sqrt(double numb)
{
	double x1,x2,x3,x4,x5,f,fx,c;
	double abs(double num);
	for(x1=0.1,x2=0,x3=0,x4=0,x5=0;;)
	{
		f=x1*x1-numb;
		fx=2.0*x1;
		x2=x1-f/fx;
		x5=x4;
		x4=x3;
		x3=x1;
		x1=x2;
		if(abs(x2-x5)<0.000000000001) break;
	}
	return(x1);
}

相关标签: c语言