Turbo C++ 4.5 giving wrong output for correct programming code to give the sum of following series : 1 + 1/1! + 1/2! +...

My Turbo C++ 4.5 is giving incorrect result for the following programming code which is meant to sum the series 1 + 1/1! + 1/2! + 1/3! upto 'n' terms.It gives the correct result for 'n=1' and 'n=2'.What is the problem in the following code? Please help.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include<iostream.h>
int main()
{ int n,i,fact=1;
  float sum=1.0,div;
cout << "Enter the value of n: ";
cin >> n;

if(n==1)
cout << "The sum of the series 1 + 1/1! + 1/2! +... upto " << n << " terms is " << sum ;
if(n!=1)
{ {for(i=1;i<n;i++)
  {fact=fact*i;
  div=(1/fact);
  sum+=div;
  }
  }
cout << "The sum of the series 1 + 1/1! + 1/2! +... upto " << n << " terms is " << sum ;
}
return 0;
}
Last edited on
Line 13: You're doing integer division.

PLEASE USE CODE TAGS (the <> formatting button) when posting code.
It makes it easier to read your code and also easier to respond to your post.
http://www.cplusplus.com/articles/jEywvCM9/
So, what should I do to resolve this?

Well, thanks. :) I will use the code tags from now onwards.
Last edited on
So, what should I do to resolve this?

Don't do integer division. :)

Integer division is causing your result to be truncated.

The integer division thing is one of those "gotchas" in C and C++.

1/2 --> 0, because the integer 1 is divisible by the integer 2 zero times.

In order to get 0.5, you need to make sure at least one of the operands is a float.

1.0/2 --> 0.5.
1/(float)2 --> 0.5.

Hope this helps.
Well, thanks. The problem has been resolved. :)
Topic archived. No new replies allowed.