0

For a school assignment we are supposed to write a short piece of code that calculates the telescopic limit up to 100. The expect answer should be sum is: 0.99000 but my output is always sum is: 0.00000 no matter what I try.

I hope it is a quick fix that I have been overlooking, but I can't, for the life of me, figure out what it is.

here is my code below:

#include <stdio.h>

int main(){

    float ans=0.0;

    for(int i=1; i<100; i++){
        ans += 1/ (i*(i+1));
    }

    printf("sum is: %.5f",ans);
    return 0;
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
wood
  • 3
  • 3
  • `1/ (i*(i+1))` is **integer arithmetic** i.e. as it takes integer operands, it will give `int` as output. – Aditi Rawat Jan 24 '18 at 07:18
  • regarding: `float ans=0.0;` This is assigning a `double` to a `float` value. Suggest: `float ans=0.0f;` Notice the trailing `f`. – user3629249 Jan 24 '18 at 09:02

1 Answers1

2

Have a look at the expression

  1/ (i*(i+1))

i is of type int, and a 1 (digits) are by default of type int (integer constants of type int, to be pedantic).

So, all the participating members are of type int and the arithmetic will be integer arithmetic. It is not floating point arithmetic. Thus, for above expression, for any value of i, greater than 0, you'll have a result of 0 as an outcome of integer division.

You need to either

  • use a float or double type operand
  • cast one of the operands to float or double

to enforce a floating point arithmetic to get the desired result.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261