-1.#IND

I've made this program to simulate the way to find square roots without a calculator and without sqrt()...no duh. But here it is. I don't understand why it doesn't work and why I'm getting that message.

By the way, if you don't know it already you can find square roots by repeating the formula : new guess = 5 * (guess + NumberYoureLookingFor / guess)

Any help would be greatly appreciated. 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
29
#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    double input, temp;
    int i;
    double array[100];
    
    
    cin >> input;
    
    temp = input / 2;
    
    array[0] = temp;
    
    for(i = 0; i < 100; i++)
    {
        array[(i+1)] = 1/2 * (array[i] + (temp / array[i]));
        cout << array[(i+1)] << endl;
    }
    
    cout << sqrt(input);
    
    system("pause");
    return 0;
    
}
The formula you give above does not match what you implemented, but in either case both are wrong.

The formula is

x[n+1] = 0.5 * ( x[n] + S / x[n] )

Line 14 should be removed.

Line 20: 1/2 == 0, not 0.5, because integer division is used. Replace 1/2 with 0.5.

Line 20: temp needs to be replaced with input.
Edit: Oops, the initial guess x[0] needs to be "somewhat close" to the real answer. I suspect this is why you were dividing the number by 2 on line 14. In which case, change line 16 to

 
array[0] = input / 2;     // initial guess = value/2 


Topic archived. No new replies allowed.