Two separate floating-point square

square root

Title Description

Given a number, write algorithm, which prescribe, the results retained 6 decimal places.

Enter a number (which can be fractional), the square root of its output, the result Reserved 6 decimal places

Topic analysis

Dichotomy floating point number, to find values ​​for alignment. In the final solution is assumed that a given upper and lower limits, and then find the median; relatively mild median size of x, and modify its upper and lower limits, followed by cycle

Code

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

// 开平方 
int main(){
	double x;
	scanf("%lf", &x);
	double l = 0, r = x;
	while(r - l >= 1e-8)	// 比保留小数位数多 2 。保留 6 位小数,则 1e-8 
	{
		double mid = (l + r) / 2;
		if(mid * mid >= x) r = mid;
		else l = mid;
	}
	printf("%lf\n", l);
	return 0;
} 

operation result

输入

3.5

输出

1.870829

to sum up

Although the simple dichotomy of thinking, but the precision needed to control, improper accuracy control, it is easy to fall into an infinite loop.

Published 64 original articles · won praise 9 · views 6377

Guess you like

Origin blog.csdn.net/qq_38496329/article/details/104740882