Ovi Berbecaru
Ovi Berbecaru

Reputation: 1

Double showing int value

I don' t understand why when i use the function in main( Serie(1), Serie(n) ), it keeps showing the result "1", although it is a double value.

double Serie(int n)
{
    double sum = 0;

    for(int i = 1 ; i <= n ; i++)
    {
        sum = sum + (1/i);
    }

    return sum;
}

Upvotes: 0

Views: 589

Answers (4)

barkha mehra
barkha mehra

Reputation: 34

As your operation (1/i) contains both values as integer(i in this case is integer). This part of the expression results in integer result. Decimals get truncated in this case.

To get the double result you can typecast either 1 or i to double.

Upvotes: 0

Sean
Sean

Reputation: 62532

The expression (1/i) is an integer division. The first time through it'll evaluate to (1/1) giving you 1. When you add it to sum there will be an integer promotion to double.

However, on all subsequent occasions (eg (1/2), (1/3) etc) your integer division will yield 0. You'll then integer promote this to a double and add it to sum which won't change it.

To fix this say (1/(double)i) or (1.0/i) to force the division to yield a double.

Upvotes: 0

Paul R
Paul R

Reputation: 213190

As already noted, you are using integer division in the expression 1/i, and the result of this will therefore be 0 for i > 1. An easy solution is to change:

    sum = sum + (1/i);

to:

    sum = sum + 1.0 / i;

or perhaps more succinctly:

    sum += 1.0 / i;

Upvotes: 4

Daniel Daranas
Daniel Daranas

Reputation: 22644

(1/i) is not a double value. 1 is an integer literal, i is an int, so 1/i performs an integer division.

When the double type sum comes into the equation, it's already too late for you.

Upvotes: 3

Related Questions