double sqrt(double a) { if (a<0) { cout << "\nsqrt(" << a << ") is imaginary\n"; return -1; } int x = a/2; // first guess (could be better) while (x*x-a != 0){ x = 0.5*x+a/(2*x); // next guess, by Newton's method } return x; }

I also tried making the while-loop-test (x*x-a>0.01 || x*x-a<-0.01) but it still only worked for perfect squares. (Oddly enough, though, it gave the exact answer for perfect squares. I expected it to limit the accuracy.)