⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 sqrt.cpp

📁 自己写的算平方根的函数sqrt
💻 CPP
字号:
// sqrt.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"

#include <stdio.h> 
#include <stdlib.h>
#include <math.h>
#define max(a,b) (((a) > (b)) ? (a) : (b))
#define eps 1e-6 //定义精度 

double mysqrt(double n) //用二分法 
{ 
	if(n<0) //小于0的按照你需要的处理 
		return n; 
	double ans; 
	double low,up; 
	low=0,up=max(n,1); 
	ans=(low+up)/2; 
	while(ans*ans-n>eps || ans*ans-n<-eps) 
	{ 
		if(ans*ans>n) 
		{
			up=ans; 
			//printf("up = %f ",up);
		}
		else 
		{
			low=ans; 
			//printf("low = %f ",low);
		}
		ans=(low+up)/2; 
		//printf("ans=%f\n",ans);

		//getchar();
	} 
	return ans; 
} 

int main(int argc, char* argv[])
{
	for(double d = 0.1; d < 7; d += 0.1)
	{
		printf("%f,diff: %f\n",mysqrt(d),mysqrt(d) - sqrt(d));
	}
	system("pause");
	return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -