nan problem? nth root algorithm

I'm trying to get this nth root algorithm to work, but i seem to being getting nan after running and inputting the number with the given nth root. any help would be appreciated. I'm very new to c++, any idea what i can do?

For example I'll input 9 and 3 for nth root:

Enter a number to find the nth root of:
9

Enter the nth root: 3

The algorithm iterated 2 times.
The approximate square root of 9 is nan



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include <iostream>
#include <complex>
#include <cmath>

using namespace std;

double babylonian (double A){
    int count1{0};
    double N;
    double temp;
    double error = .00001;
    double x=A/2; //guess value = number/2
    temp=((A/pow(x,N-1))+(x*(N-1)))/N;
    while (abs(x-temp)>error){
        x=temp; //record of old into new
        temp=((A/pow(x,N-1))+(x*(N-1)))/N;
        ++count1;

    }

    cout<< "\nIt iterated "<< count1 <<" times.";
    return (temp);
    
    
}
int main (void){
    double N;
    double A;
    cout<< "Enter a number to find the nth root of: \n";
    while(cin>> A){
        cout<<"\nEnter the nth root: ";
        cin>> N;
        cout<< "\nThe approximate square root of "<< A <<" is "<< babylonian(A);
        cout<< "\n\nEnter a number to find the nth root of: ";
    }
}
Hi,

You must pass the N as an argument to your function. N on line 9 is a local variable, and is different to N in main()

Avoid having 'magic' numbers like 0.00001 in your code, make them a const variable instead.

It's a very good idea to always initialise your variables to something, preferably at the same time as declaration. Note that 0 is not always a good idea, but might be Ok most of the time.

Don't have line 5: Google to see why not, and what to do instead.

With the file layout, put your function declarations before main(), and the function definitions after main() . This helps the compiler, and means that main() is always easy to find.

Hope all goes well :+)
Thanks! After some tinkering I understood what you meant about the N, it works now. :D
Topic archived. No new replies allowed.