Amir Bhandari
Amir Bhandari

Reputation: 107

How to sum up fractions from integer divisions inside a float variable?

I am writing a simple C program that prints the sum of the harmonic series like:

1 + 1/2 + 1/3 + ...... + 1/n

My program is:

#include<stdio.h>
void main(){
     int n,i;
     float num=0, tmp=0;
     scanf("%d", &n);
     for(i=1;i<=n;i++){
        tmp = 1/i;
        num = num + tmp;
     }
     printf("%f", num);
}

As per my understanding, if n=4, the output must be: 2.03333 But the output comes as 1.00000

Upvotes: 0

Views: 157

Answers (2)

Yunnosch
Yunnosch

Reputation: 26703

1/i is not a float value, it is an int of value 0 or 1, because of integer division rules.
The value is 1 for 1/1 otherwise 0. Adding all of them up results in 1.

This is a floating point value:

1.0/i

Adding them up should give the desired result.

To be precise, I should say that 1.0 is a double.
In order to work with actually a float value to match the float variable, use 1.0f. Both are floating point values in contrast to integer values.

Upvotes: 4

OmG
OmG

Reputation: 18838

As 1 and i are integers, dividing these two will be integer and you will get 0 for i > 1 in this case. You can cast i using (float)i and you will have 1/(float)i.

Upvotes: 3

Related Questions