【数据结构与算法】开根号

开根号

#include <iostream>
#include <stdio.h>
using namespace std;

double myqrt(double x) {
	if (x < 0)
		return -1;
	constexpr auto eps = 1e-8;
	double low, up, mid, last;
	low = 0;
	up = ( x >= 1 ? x : 1);
	i0
	mid = (low + up) / 2;
	do {
		if (mid * mid > x)
			up = mid;
		else
			low = mid;

		last = mid;
		mid = (up + low) / 2;

	} while (abs(mid - last) > eps);
	return mid;
}

int main() {
	std::cout << myqrt(0.8) << std::endl;
	return 0;
}

 

posted @ 2021-09-11 20:15  苏格拉底的落泪  阅读(150)  评论(0编辑  收藏  举报