Recursive harmonic function returns NaN

I wrote the following code example 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 find out why this is 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

+3
source share
2 answers

I think you want to do:

return harmonic(n-1, (har+(1/n)));
+10
source

, float , "if (n == 0)" "if (n <= EPSILON)" "if (n == 1)" "if (n <= 1,0f + EPSILON)", EPSILON , , 1,0e-5. , .

, n int. . "n" , .

double float.

, NaN. "else", , , . , NaN.

+2

Source: https://habr.com/ru/post/1734892/


All Articles