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
*/
#include <iostream>
usingnamespace 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;
}
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...