11.2—分治法—Sqrt(x)

来源:互联网 发布:社交网络剧情 编辑:程序博客网 时间:2024/05/19 20:00
描述
Implement int sqrt(int x).
Compute and return the square root of x.

#include<iostream>#include<vector>#include<cmath>#define eps 0.000001using namespace std;bool flag = true;vector<double> Sqrt(double a){if (a < -eps){cerr << "输入错误!" << endl;flag = false;return vector < double > {-1, -1};}else if (abs(a) <= eps)return vector < double > {0, 0};else{double x0 = 5;double y0 = x0*x0 - a;while (abs(y0) > eps){double x = x0 - y0 / (2 * x0);double y = x*x - a;//===x0 = x;y0 = y;}return vector < double > {x0, -x0};}}int main(){double a =9;vector<double> res = Sqrt(a);if (flag)cout << res[0] << " " << res[1] << endl;}

原创粉丝点击