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?