Sdasd Sdaf
Sdasd Sdaf

Reputation: 23

Unexpected result of expressions with division

I have to write a program which calculates and displays the following expression:

P=(1/2-3/4)*(5/6-7/8)*...*[n/(n-1) - (n+2)/(n+3)]

I did this and I ran it and it shows no errors. When I run it, for every value that I enter, it shows P=0. What is wrong?

#include <stdio.h>

int main (void)
{
    float s, p=1.0;
    int i, n;
    printf("Enter a number:");
    scanf("%d", &n);
    for (i=1;i<=n;++i) { 
        p*=((i)/(i+1)-(i+2)/(i+3));
    }
    printf("p=%f\n", p);
}

Upvotes: 2

Views: 179

Answers (4)

Jack
Jack

Reputation: 133587

You are using int variables, not float variables, thus i/(i+1) and (i+2)/(i+3) will always evaluate to 0 since it's integer division.

Just use some casts to force the evaluation using floating point arithmetics:

((float)i)/(i+1)-((float)i+2)/(i+3)

Upvotes: 2

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726639

It is not working because i is integer: when you divide (i)/(i+1) or (i+2)/(i+3), you get a zero in both cases, because when i is positive, denominator is greater than numerator. Zero minus zero is zero, p times zero is zero, so that's what you get.

To fix this problem, declare i as float:

#include <stdio.h>
int main ()
{
    float s,p=1.0, i;
    int n;
    printf("Put a number:");
    scanf("%d",&n);
    for (i=1;i<=n;++i) { 
        p*=((i)/(i+1)-(i+2)/(i+3));
    }
    printf("\n p=%f",p);
    return 0;
}

Upvotes: 2

Carl Norum
Carl Norum

Reputation: 224962

Your problem is that integer division truncates rather than returning the floating point results you appear to be looking for:

 i/(i+1)

and

 (i+2)/(i+3)

are always 0 in C.

Upvotes: 1

Paul R
Paul R

Reputation: 212979

You're using integer arithmetic rather than floating point, so the division operations are being truncated.

Change:

p*=((i)/(i+1)-(i+2)/(i+3));

to:

p*=((float)(i)/(i+1)-(float)(i+2)/(i+3));

Upvotes: 6

Related Questions