Search code examples
c++functionsqrt

How to write and implement your own function


I need to write my own sqrt function: double my_sqrt_1(double n) How would I go about doing this? At first I tried putting this outside of "int main()":

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

I then put this:

int main()
{
    cout << "Please enter a value ";
    cin >> my_sqrt_1;
    cout << '\n' << x;
}

I also tried:

int main()
{
    cout << "Please enter a value ";
    cin >> my_sqrt_1;
    cout << '\n' << my_sqrt_1;
}

None of this worked though. I'm probably doing this completely wrong, but it made sense in my head.


Solution

  • "I'm probably doing this completely wrong ..."

    Sorry to say that, but yes.

    You need a variable to receive input, and call your function passing that variable

    int main() {
        cout << "Please enter a value ";
        double myNumber;
        cin >> myNumber;
        cout << '\n' << my_sqrt1(myNumber) << endl;
    }
    

    Also your function is supposed to return the result of the calculation

    double my_sqrt_1(double n) {
        double x = 1.0;
     // ^^^^^^      ^^
        x = (x + n / x) / 2.0;
                        // ^^
        return x; // <<<<<<<<<<<<<<
    }