-3

Why, when I use double i the output is (an approximation to) the value of e?

#include <iostream>
using namespace std;
int main ()
{
    double s=0;
    double i=1;
    for (int m=1;m<5;m++)
    {
        i=m*i;
        s=s+1/i;
    }
    cout<<s+1;
    return 0;
}

But when I use int i, the output is 2:

#include <iostream>
using namespace std;
int main ()
{
    double s=0;
    int i=1;
    for (int m=1;m<5;m++)
    {
        i=m*i;
        s=s+1/i;
    }
    cout<<s+1;
    return 0;
}

The variable that stores the value of e is s, which is double, so I was expecting that the datatype of i doesn't matter.

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83

2 Answers2

-2

You're doing integer division on this line when i is an integer:

s=s+1/i;

You want to instead do floating point division:

s = s + 1.0 / i;
Blindy
  • 65,249
  • 10
  • 91
  • 131
-2

The reason that the output is different when you use double or int for the i variable is because of the way that division works in C++. When you use integer division, the result of the division is also an integer. So, in the second example where i is an int, each time you perform the division 1/i, the result is always an integer, which is then converted to a double and added to s. This means that some of the fractional parts of the calculation are being lost.

In the first example, where i is a double, the result of the division 1/i is also a double, and the fractional parts of the calculation are preserved. This is why the output is different in the two cases.

One way to fix this would be to use the 1.0 instead of 1 in the division, like this:

#include <iostream>
using namespace std;
int main ()
{
    double s=0;
    int i=1;
    for (int m=1;m<5;m++)
    {
        i=m*i;
        s=s+1.0/i;
    }
    cout<<s+1;
    return 0;
}

This way, the 1.0 will be treated as a double, and the result of the division will also be a double, so the fractional parts of the calculation will be preserved.

Dan
  • 744
  • 1
  • 8
  • 23