0

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

2
Contributors
2
Replies
3
Views
5 Years
Discussion Span
Last Post by FelineHazard
0

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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.