Hello,
I am writing a program that will repeatedly calculate (loop) using the formula
nextGuess = 0.5(lastGuess + number/lastGuess).
I need a function using this calculation, and I need some inputs: the number, the first guess from the user.
Then, the difference will be calculated between the value of nextGuess and the value of lastGuess. If the difference is < 0.005, the loop ends.
Here is the code I have written, so far. It compiles, but definitely doesn't do what I want.
Code:
#include <stdio.h>
#include <math.h>
void instruct( void );
double nextGuess (double number, double guess, double lastGuess );
int main( void )
{
double number,
answer,
guess,
difference,
newGuess,
lastGuess;
instruct ();
printf ( "\n\n Enter a real number that you wish to have the square root calculated: \n\n" );
scanf ( "%lf", &number );
if ( number < 0 )
printf ( "\n\n I'm sorry but negative numbers don't work in this equation. \n\n" );
else if ( answer = (sqrt(number)))
printf ( "\n\n Enter your guess for the square root of %.5lf: \n", number );
scanf ( "%lf", &guess );
do
{
// newGuess = 0.5 * ( lastGuess + newGuess / lastGuess )
guess = nextGuess(number, guess, lastGuess);
difference = answer - guess;
}
while( difference > 0.005 || difference < -0.005 );
printf ( "\n\n Congratulations, your guess was within 0.005 of the square root of %.5lf!!!!! \n\n", number );
return 0;
}
void instruct( void )
{
printf ( "\n\n You will give a number, N, which will then have its square root calcuated. You will then insert guesses as to what you think the square root is and when are you within 0.005 of the correct answer you will have completed the situation. \n" );
}
double nextGuess (double number, double guess, double lastGuess )
{
double newGuess;
newGuess = 0.5 * (lastGuess + newGuess/ lastGuess);
return (newGuess);
}
Thanks for any help! I'm fairly new to programming, so I am kind of lost as to how to fix it...
Sarah