Dividing 1/n always returns 0.0

user1809300 picture user1809300 · Nov 11, 2012 · Viewed 17.1k times · Source

I am trying to calculate p1=(1/1)*(1/2)*...*(1/n) but something is wrong and the printf gives me 0.000...0

#include <stdio.h>

int main(void) {

    int i,num;
    float p3;

    do {
        printf ("give number N>3 : \n" );
        scanf( "%d", &num );
    } while( num <= 3 );

    i = 1;
    p3 = 1;  

    do {
        p3=p3*(1/i);
        printf( "%f\n",p3 );
    } while ( i <= num );

    printf("\nP3=%f",p3);
    return 0;
}

Answer

Daniel Fischer picture Daniel Fischer · Nov 11, 2012
(1/i)

i is an int, so that's integer division, resulting in 0 if i > 1. Use 1.0/i to get floating point division.