views:

160

answers:

2

Hi,

I have written the following sample code to find the harmonic value of N. (1+1/2+1/3+...1/N). Read the comments in the code written in BOLD and help me to find why is this happening.

#include <stdio.h>

float harmonic(float n, float har) {

    if(n==0) {
        return 0;
    }

    if(n==1) {
        printf("%f\n", har+1.0f);***/* This prints value 1.5000*/***
        return har+1.0f;
    }else{
        harmonic(n-1, (har+(1/n)));
    } 
} 

int main() 
{ 
    printf("%f\n", harmonic(2, 0.0f)); **/* But this prints value nan(Not a  Number)*/**  
    return 0; 
}

Thanks, Naga

+10  A: 

I think you want to do:

return harmonic(n-1, (har+(1/n)));
Matthew Flaschen
+2  A: