Help on sqrt program

HElP!
Write your own square root function named double my_sqrt_1(double n) using the following pseudocode:
x = 1
repeat 10 times: x = (x + n / x) / 2
return x
and then write a main which prints n, sqrt(n), and my_sqrt_1(n) for n = 3.14159 times 10 to the kth power for k = -100, -10, -1, 0, 1, 10, and 100. Use this C++11 code (which only works on linux2):
for(auto k : {-100, -10, -1, 0, 1, 10, 100}){
n = 3.14159 * pow(10.0, k);
//cout goes here
}
Note: my_sqrt_1(n) is based on the Newton-Raphson algorithm

and this is what i have so far but im so lost as i am a complete beginner at programming nevertheless at c++.

#include "std_lib_facilities_3.h"

double my_sqrt_1 (double n)
{
int x=1;
x = (x+n/x)/2;
return x;
}

int main ()
{
for (auto k: {-100, -10, -1, 0, 1, 10, 100}){
n= 3.14159*pow(10.0, k);
cout << n << " , " << sqrt(n) << " , " << my_sqrt_1(n)\n;
}
}
Within the function my_sqrt_1(), you have omitted to implement this part of the specification: "repeat 10 times". Variable x needs to be of type double, not int.

In main(), variable n is used without being defined and given a type.
so i would have to declare 'double n=3.14159' before the 'for (..)' ?
and also how can i repeat the function 10 times? with a while loop?
> with a while loop?

A for loop is more convenient when we want to repeat something N times.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
double my_sqrt_1 (double n)
{
    double x = 1 ;

    // repeat 10 times
    for( int i = 0 ; i < 10 ; ++i ) x = (x+n/x)/2 ;

    return x;
}

int main ()
{
    for (auto k : { -100, -10, -1, 0, 1, 10, 100 } )
    {
        double n = 3.14159 * pow( 10.0, k ) ;
        cout << n << " , " << sqrt(n) << " , " << my_sqrt_1(n) << '\n' ;
    }
}
ohhh! i see thats where incrementing i is used in! thank you it makes much more sense now !
Topic archived. No new replies allowed.