Dividing 1/n always returns 0.0 [duplicate]
Asked Answered
F

3

7

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;
}
Forgetful answered 11/11, 2012 at 12:19 Comment(4)
The division in p3*(1/i) is integer division. Try p3 * (1.0 / i) instead. Oh ... and use double rather than float for your floating-point numbers.Rodmun
Isn't the second loop infinite? It waits for a condition to be met on i and num, yet it does not alter either one of them.Intact
sorry i didnt copy the entire codeForgetful
What about doing p3 /= i; instead? ;-)Trapp
H
15
(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.

Humidistat answered 11/11, 2012 at 12:21 Comment(0)
T
6

1 is an integer, i is an integer. So 1/i will be an integer, ie the result will be truncated. To perform floating-point division, one of the operands shall be of type float (or, better, of type double):

p3 *= 1. / i;
Toomin answered 11/11, 2012 at 12:21 Comment(2)
and why double instead of float?Forgetful
@Forgetful it has more precision.Welter
M
2

I had the same issue. The basic case:

  • when you want to get float output from two integers, you need to convert one into float

    int c = 15; int b = 8; printf("result is float %f\n", c / (float) b); // result is float 1.875000 printf("result is float %f\n", (float) c / b); // result is float 1.875000

Magnetograph answered 22/5, 2017 at 14:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.