【数据结构与算法】开根号
开根号
#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; }