Reputation: 299
I have this code which I wrote for calculating the following series:
Let me explain the problem: We input integer n and long double x. Now, the function calculates the value of the above radical.
The code is:
//nested sqrt function
#include <iostream>
#include <math.h>
using namespace std;
long double seq( unsigned long, long double, unsigned long = 0 );
int main() {
unsigned long n = 0;
long double x;
cout << "Enter integer n: ";
cin >> n;
cout << "Enter x: ";
cin >> x;
cout << seq( n, x);
return 0;
}
long double seq( unsigned long n, long double x, unsigned long i = 0 ) {
long double res = 0;
if( i == n) {
return res;
}
else {
res = sqrt( pow( x, i) + sqrt( seq(n, x, i+1)));
}
}
The code is not executing and is showing a type error for function, but I gave pass correct type to the function.
This is the error that I get:
In function 'long double seq( long unsigned int, long doublem long unsigned int)':
nested.cpp:25:70: error default argument given for parameter 3 of 'long double seq(...)' [-fpermissive]
nested.cpp:8:13: error: after previous specification in 'long double seq(...)' [-fpermissive]
Also, is my approach correct for solving this problem?
EDIT I am unable to comment, but what I was saying is preference bean (thanks!) gave the answer anf that removed the error. But now one proble is even deeper, this code is actually not providing desired result. I input n = 10 and x = 2, the output was nan. The output is nan for any value of x or n that I input. Please tell me where I am going wrong in creating the function.
Thanks everyone it was a small mistake that you all pointed out generously: as lutzl said, I changed the if condition and also, removed the two square roots. You are right it was very incorrect earlier, as it was adding extra sqrt function. Also res was redundant. Thank you.
Upvotes: 2
Views: 1474
Reputation: 26040
If you want to get the correct result, use
long double seq( unsigned long n, long double x, unsigned long i) {
return sqrt( pow(x,i)+(i==n?0:seq(n,x,i+1)) );
}
To avoid using the power function, use a recursion
long double seq( unsigned long i, long double x, long double xpow) {
return sqrt( xpow+(i==0?0:seq(i-1,x,xpow*x)) );
}
called as seq(n,x,1)
. Or hide again the 1
in the default argument.
Upvotes: 2
Reputation: 23324
You don't return anything in your function if i != n
. Try this:
long double seq( unsigned long n, long double x, unsigned long i = 0 ) {
if( i > n) {
return 0.0;
}
else {
return sqrt( pow( x, i) + seq(n, x, i+1));
}
}
Upvotes: 2
Reputation: 385264
You can only provide a parameter default once.
I'd keep it in the declaration, but change unsigned long i = 0
in the definition to unsigned long i
.
You are permitted to do it the other way around if you like, but I don't really see the point.
Upvotes: 3