Bharath Krishna
Bharath Krishna

Reputation: 37

Unexpected output in cpp program

#include<iostream>
#include<math.h>
using namespace std;

int main()
{
    int temp = 0, n = 1100, x = 0, t2 = 0, l = 10;
    while(temp < n)
    {
        t2 = temp;

        temp += pow(l, ++x);

        cout << t2 << " " << temp << " " << x <<endl;

    }

    return(0);
}

The output obtained is :

0 10 1 
10 109 2
109 1109 3

but I expect the output :

0 10 1
10 110 2
110 1100 3

Why this difference ?..please help ..I cant find out the problem

Upvotes: 1

Views: 121

Answers (2)

yasen
yasen

Reputation: 1260

By default pow returns double. This means that when you use the expression temp += pow(l, ++x); there is a hidden cast from double to int, in order to match the type of temp.

Doubles do not have an exact representation (like ints). Therefore, the double value for 100 can be something like 99.999999..99832. When this value is converted to int, only the number before the decimal point is taken into account. Thus, the corresponding value for 100 will be 99. You can correct this by adding some very small value (like epsilon in mathematics):

while(temp < n)
{
    t2 = temp;
    double d = pow(l, ++x);
    cout << (int) d << endl;
    cout << (int) (d + 1e-10) << endl;  // 1е-10 is 0.0000000001

    temp += (int) (d + 1e-10);
}

Upvotes: 0

ThomasMcLeod
ThomasMcLeod

Reputation: 7779

Don't use pow for integer arithmetic. Try

#include<iostream>
#include<math.h>
using namespace std;

int main()
{
    int temp = 0, n = 1100, x = 0, t2 = 0, l = 10;
    while(temp < n)
    {
        t2 = temp;

        int t3 = 1, t4 = 0;
        ++x;
        while (t4++ < x) t3 *= l; 
        temp += t3;

        cout << t2 << " " << temp << " " << x <<endl;

    }

    return(0);
}

// or alternatively

#include<iostream>
#include<math.h>
using namespace std;

int main()
{
    int temp = 0, n = 1100, x = 0, t2 = 0, l = 10;
    while(temp < n)
    {
        t2 = temp;

        temp += floor(pow(l, ++x) + .5);

        cout << t2 << " " << temp << " " << x <<endl;

    }

    return(0);
}

Upvotes: 1

Related Questions