C++ confusion

Okay so 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. Any hints would be much appreciated!


/* 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
*/

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
#include <iostream>
using namespace std;

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

int main ()
{
	double number,y,root;

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


	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 root (double number, double last)
{
	double difference=1, next, last=1, number;

	if(difference < .000001)
	{
		next=number;
	}
	else
	{	
		next = 0.5*(last  - number/last); 
		difference = next - last;
		last = next;
		next = root (next,last);
	}
	return next;
}

Last edited on
Your root function has a lot of mistakes.
You should specifically tell the problem you are having with this program.

So about the root function:
1. Why are you creating a variable number & last twice? (once as parameters & once on line 38).
1.1. If you want to set their values, so do in a separate statement.
1.2. Otherwise, you should rename them.
2. You are setting the difference as 1 (It is ALWAYS be 1, by the time it reaches line 40.).
So if it is, 1, the statement, next = number will NEVER execute...
Topic archived. No new replies allowed.