Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dividing 1/n always returns 0.0 [duplicate]

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;
}
like image 392
user1809300 Avatar asked Nov 11 '12 12:11

user1809300


People also ask

How do you divide floats?

To divide float values in Python, use the / operator. The Division operator / takes two parameters and returns the float division. Float division produces a floating-point conjecture of the result of a division. If you are working with Python 3 and you need to perform a float division, then use the division operator.

How do you divide integers in Java?

Java does integer division, which basically is the same as regular real division, but you throw away the remainder (or fraction). Thus, 7 / 3 is 2 with a remainder of 1. Throw away the remainder, and the result is 2. Integer division can come in very handy.

What will happens in integer division in C?

Integer division yields an integer result. For example, the expression 7 / 4 evaluates to 1 and the expression 17 / 5 evaluates to 3. C provides the remainder operator, %, which yields the remainder after integer division.


3 Answers

(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.

like image 51
Daniel Fischer Avatar answered Sep 30 '22 22:09

Daniel Fischer


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;
like image 39
md5 Avatar answered Sep 30 '22 23:09

md5


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

like image 43
Max Makhrov Avatar answered Sep 30 '22 21:09

Max Makhrov