squareRoot functions don't work fine

I have to calculate the hypotenuse of a triangle and I need a function that returns the square root of its argument. But I don't want to use <cmath>, I want to do this on my own. The problem is that my function is returning the right number plus 0.1 (in case the double overloaded function). My int function works fine.

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>

using namespace std;

double squareRoot(double x){
    if(!(x > 0)){
        return 0;
    }

    double r;

    for(r = 0.1;; r += 0.1){
        if((r * r) >= x){
            return r;
        }
    }
}

int squareRoot(int x){
    if(!(x > 0)){
        return 0;
    }

    double r;

    for(r = 0.1;; r += 0.1){
        if((r * r) >= x){
            return (int)r;
        }
    }
}

int main(int argc, char *argv[]) {

    int i = 144;
    double d = 64.0;

    cout << "The square root of " << i << " is: " << squareRoot(i);
    cout << "\nThe square root of " << d << " is: " << squareRoot(d);

    return 0;
}


How do I fix this? Sorry for my poor english.
Change line 14 to return r-0.1;

There are some fast algorithms to compute the square root that are easy to implement. You may want to try one of those.
Thanks a lot dhaylen, I once have tried return r-0.1; but it didn't worked. Don't know why but it works fine now. Thanks.
Topic archived. No new replies allowed.