Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Data types int and double in calculating e

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading