Hi all,
I encountered some weird act from the return(); function. I'm doing some book exercise in recursions:
write a recursive function that makes a summation 1 + 1/2 + 1/3 + 1/4 + ... + 1/n. Rather basic. So I wrote this:
float summation(int n) {
if (n == 1) {
cout<<"1/"<<n<<" ";
return(1/n);
} else {
cout<<"1/"<<n<<" + ";
return( 1/n + summation(n-1));
}
}
int main() {
float sum=summation(5);
cout<<"= "<<sum<<"\n";
}
Surprisingly, the output is 1/5 + 1/4 + 1/3 + 1/2 + 1/1 = 1
But when I slightly change the recursion to explicitly state float conversion, everything works out fine!
float summation(int n) {
if (n == 1) {
cout<<"1/"<<n<<" ";
return((float)1/n);
} else {
cout<<"1/"<<n<<" + ";
return( (float)1/n + (float)summation(n-1));
}
}
Now the output is (correct): 1/5 + 1/4 + 1/3 + 1/2 + 1/1 = 2.28333
Why does including (float)
make the difference? My function is already defined as float, so why does return insists of converting values to int, when I explicitly told it I want to return float? The function is already defined as float! :\
Seriously, what gives? Can't I trust return not to mess up with my variable types?
Thanks a bunch,
-FH