Q:

Looping with double vs int

I am trying to figure out why i get two different outputs for seemingly similar loops. I think it has something to do with looping with doubles versus ints, but I am not sure. 
This code outputs 4:
int num = 10;
int cost;
int counter = 0;

for (cost = 1; cost <= num; cost += 1){
    counter += 1;
    num -= cost;
}

cout << counter << endl;

This is the output for this section:
Current Cost: 1
Remaining: 9
Current Cost: 2
Remaining: 7
Current Cost: 3
Remaining: 4
Current Cost: 4
Remaining: 0
4 candies; 0 left over

This code outputs 3:
double num = 1.0;
double cost; 
int counter = 0;

for(cost = 0.1; cost <= num; cost += .1) {
    counter +=1;
    num -= cost;
}

cout << counter << endl;

Edit:
This is the output for this code when I tried debugging it:
    Current Cost: 0.1
    Remaining: 0.9
    Current Cost: 0.2
    Remaining: 0.7
    Current Cost: 0.3
    Remaining: 0.4        
    3 candies; 0.400000 left over

Why is there a difference between the two?

A:

I probably should not be doing this, but I debugged your code and the double loop fails in the 4th iteration:
Both cost and num take the values of 0.4, but:
cost <= num;

evaluates to false;
This is due to the nature of doubles being stored with so much precision.
I would suggest avoiding ==, >= and <= statements when dealing with doubles.
A solution would be to convert your loop to:
for(cost = 0.1; cost < num+0.001; cost += .1) {
    counter +=1;
    num -= cost;
}

therefore solving the precision issue, but I would recommend against it as it could lead to problems in a more complex environment.

