Recursive function problem

Im trying to create a program that will employ a recursive that will estimate the square root of a number using the approximation

NextGuess = 0.5(LastGuess - Number/LastGuess)

Here's what I have so far but i'm not sure where to go from here because it always outputs -1 as the answer.

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
/* Create a program that uses a recursive function to estimate the
   square root of a number. 
   input: number user wants square root of
   output: Square root of number and number itself
   processing: nextguess = .5(lastguess-number/lastguess)
			   check that value is greater than 0 using function
*/

#include <iostream>
using namespace std;

int ifzero(double a);
int rooter (double y, double last,double);

int main ()
{
	double number,y,root,fin=1;

	cout<<"Enter the number of which you want to calculate the square root.";
	cin>>number;
	y = ifzero(number);
	root = rooter(y,fin,1);
	cout<<"The square root of "<<y<< " is approximately "
		<< root<< ".";

	system ("pause");
	return 0;
}

int ifzero(double a)
{	
	while(a>0)
	{
	return a;
	}
	while(a<=0)
	{
		cout<<"Enter the number of which you want to calculate the square root.";
		cin>>a;
	}

}

int rooter (double numb, double final, double difference)
{
	double next,number;

	if(difference < .000001)
	{
		next=numb;
	}
	else
	{	
		next = 0.5*(final  - numb/final); 
		difference = abs (next - final);
		final = next;
		next = rooter (next,final,difference);
	}
	return next;
}
I think that your initial formula is wrong: instead of nextguess = .5(lastguess-number/lastguess)
should be nextguess = 0.5(lastguess+number/lastguess). See for an example http://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method

Also, why do rooter() and ifzero() return int instead of double?
Last edited on
Topic archived. No new replies allowed.