So I've been starting to make a Cash Register program which will take in what the user is paying and how much the object costs. This will tell the user how much coins (Toonies, loonies, etc.) they'll get in return. Here's the part of the code that determines how much coins the user will get in return:
if(amountPayed >= amountToPay) {
remainder = amountPayed - amountToPay;
while(remainder > 0) {
if(remainder >= 2) {
toonies++;
remainder = remainder - 2;
System.out.println(remainder);
}
else if(remainder >= 1) {
loonies++;
remainder = remainder - 1;
System.out.println(remainder);
}
else if(remainder >= 0.25) {
quarters++;
remainder = remainder - 0.25;
System.out.println(remainder);
}
else if(remainder >= 0.1) {
dimes++;
remainder = remainder - 0.1;
System.out.println(remainder);
}
else if(remainder >= 0.05) {
nickels++;
remainder = remainder - 0.05;
System.out.println(remainder);
}
else if(remainder >= 0.01) {
pennies++;
remainder = remainder - 0.01;
System.out.println(remainder);
}
}
I've been having a problem with getting the correct amount, the loop ended up being infinite. I thought to myself, this can't be true as I made sure that all the values would go through evenly.
I decided I should do some debugging so I made it output the remainder everytime it went through. Here's what I got:
18.01
16.01
14.010000000000002
12.010000000000002
10.010000000000002
8.010000000000002
6.010000000000002
4.010000000000002
2.0100000000000016
0.010000000000001563
1.5629858518551032E-15
This was very weird to me because the numbers I entered only went to the second decimal. I was subtracting the numbers from the remainder just fine. So what's my problem?