## FelineHazard Newbie Poster

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

## Ancient Dragon 5,243

Why does including (float) make the difference?

Because 1/2 is integer digision, and 1 divided by 2 is 0. Make it float in a couple ways: 1) 1.0F/2.0F or 2) (float)1/2, or 3) 1.0F/2, or 4) 1/2.0F. Any of those methods are ok, just a matter of personal preference.

## FelineHazard

Thanks for the über-quick reply. That's one to remember.
-FH