1

code below.

I'm writing an algorithm that sums the series 1.2 + 2.3 + 3.4 + 4.5 + 5.6 + 6.7 + 7.8 + 8.9 + 9.1 + 10.11...

as it is relatively short I shall post the whole code:

    #include <iostream>

using namespace std;

int main()
{
    int num;
    double dec = 12, sum, denom, temp;
    cout << "input the last integer between 1 to 98 without "
        << "fraction you want to add: ";
        cin >> num;
    for (int i = 1; i <= num; i++)
    {
        denom = 10;
        dec += 11;
        temp = dec/denom;
        //cout << temp - int(temp) << endl;
        if ((temp - int(temp)) == 0.9)
        {
            dec -= 9;
        }
        cout << dec/denom << " + ";
    }
}

what I am confused about is this bit here:

//cout << temp - int(temp) << endl;
        if ((temp - int(temp)) == 0.9)

removing the comment shows that temp - int(temp) does eventually = 0.9 yet the conditional statement does not seem to ever become true. what am I missing??

I am not asking for a better method, or solution, just an answer to this specific problem. Thank you.

Ben Jenney
  • 75
  • 6
  • 2
    This is probably an excersise to make you learn that comparing double for equality is a bad idea because of rounding. You should reimplement this algorithm in integer arithmetic and at best convert to double for later in the algorithm. – alfC Dec 13 '18 at 05:12
  • 1
    [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – R Sahu Dec 13 '18 at 05:12

0 Answers0