i am writing a program for my introduction to c++ (and programming) class that has us writing code that determines the square root of a number using the formula ng = .5 (lg +n/lg). its supposed to be where n = the number we want to find the square root of, ng - next guess and lg is last guess. the program is supposed to start with a last guess of 1, and plug that into the formula, with the number we want the square root of, and basically keep looping back, replacing last guess with next guess each time until the diffrence between the two is less then .005 which then indicates the square root....i.e. if we want the square root of 100, then the first run through the formula would leave us with 55.5 (lg = 1, n = 100), then the program would loop back, and replace the 1 with 55.5 and recalculate, until it reached 10 +- .005, and display this. i have most of the code written, and thus far it works, but am uncertain as to how to get the program to loop back to the formula. i will post the code here after and am wondering if someone can point me in the right direction
//square root.cpp
// this program calculates the square root of a number useing ng=.5*(lg+n/lg)
#include <iostream>
#include <cmath>
using namespace std;
float n;
float ng;
float lg = 1.0;
float diff;
void main ()
{
cout <<"this program calculates the square root of a number." << endl;
cout <<"please enter what number you would like to know the square root of:";
cin >> n;
ng = .5*(lg+n/lg);
diff = ng - lg;
if (diff > .005)
{
lg = ng;
}
else
{
cout << "the square root is " << ng << endl;
i have also tried it like this but the result ends up incorrect:
//square root.cpp
// this program calculates the square root of a number useing ng=.5*(lg+n/lg)
#include <iostream>
#include <cmath>
using namespace std;
float n;
float ng;
float lg = 1.0;
float diff;
void main ()
{
cout <<"this program calculates the square root of a number." << endl;
cout <<"please enter what number you would like to know the square root of:";
cin >> n;
ng = .5*(lg+n/lg);
diff = ng - lg;
while (diff >= .005)
{
lg = ng;
ng = .5*(lg+n/lg);
diff = ng - lg;
}
cout << "the square root is: " << ng << endl;
}
this loops, but ends up displaying a incorrect result i.e. 100 square root = 26.2401
code tags, my main man, code tags. What you are looking for is a do while loop. It's going to look like:
1 2 3 4 5 6
//initialize, and get user input
do{
//update last guess, to reflect that it is the current guess
//do the code to produce the next next guess
while( abs(ng - lg) > epsilon) //this line will loop back up to line 2, as long as the current absolute value of the difference is greater then the allowed variance (epsilon)
//clean up, output the final guess
After thoughts: limit the number of guess you can make, so that you won't have run away cases, validate input against negative numbers, and modify the code so that it works for numbers between 0 and 1.