Square Root Function

Ok I have no idea if my function is working. Currently its suppose to guess the square root of a number up to the threshold of 0.0001 but the program is crashing when I type in a number. But when I type in 1 it returns 1 as the square root. Anything higher would crash it. I want to know is whether the code is wrong or is that the computer cant handle it. Thanks

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
double root(double x){
       double y, y1 = 0, y2 = x+1;
       if(x < 0) 
            cout << "Unable to Square Root negative Number";
       else
           y = y1+y2/2;
           if(y2>x){
                 y2=y;
                 }
           if(y*y-x <= 0.0001 && y*y-x >= -0.0001){
                 return y;
                 }
           else{
                 y1=y;
                 }
           y = y1+y2/2;
           root(x);
           
}
int main() {
    
double value;
cout << "Enter number to be square rooted" << endl;
while(cin >> value)
cout << root(value) << endl;
system ("pause");

}
Sometimes, it's best to use what the language has built in i.e, math functions. Try this, it is a lot less lines of code and it runs very clean.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream>
#include <math.h>
using namespace std;

int main() {
    start:
    cout << "Enter a value to be square rooted\n";

double value, root;
  cin >> value;
  if (value < 0) {
      cout << "Negative intergers cannot be squared\n";
      goto start;
  }
  root = sqrt (value);
  cout << (sqrt, value, root );
  return 0;
}
Using goto is a bad programming style. Use loops instead.
Don't create multiple threads for the same problem. http://cplusplus.com/forum/beginner/57297/
Topic archived. No new replies allowed.