I am learning C++, working through the books recommended by this website. I'm trying to code Exercise 6-3 of Practical C++ Programming. Here's the problem:
Given an amount less than $1.00, compute the number of quarters, dimes, nickels, and pennies needed.
Here's my code:
Code:
#include <iostream>
int main(){
float money; // amount of money
int quarters, dimes, nickels, pennies; // Stores the amount of each coin needed.
while (true){
std::cout<< "Enter a non-negative amount of money " // Prompt user for money
<< "less than $1.00, or -1 to stop: "; // amount
std::cin >> money;
if (money == -1) // Loop until user enters -1
break;
if (money < -1 || money >= 1.0) // Start loop over if money
continue; // amount is invalid.
std::cout << "$" << money << " in change is ";
quarters = (money / 0.25); // Stores the amount of quarters needed, then subtracts
money -= (quarters * 0.25); // that amount in cents from the money total.
dimes = (money / 0.1); // Stores the amount of dimes needed, then subtracts
money -= (dimes * 0.1); // that amount in cents from the money total.
nickels = (money / 0.05); // Stores the amount of nickels needed, then subtracts
money -= (nickels * 0.05); // that amount in cents from the money total.
pennies = (money * 100); // Money is in cents, so it is multiplied by 100 to convert
// it to the amount of pennies needed.
std::cout << quarters << " quarters, " << dimes << " dimes, "
<< nickels << " nickels, " << " and " << pennies << " pennies.\n";
}
return 0;
}
For some reason, it's not calculating the right amount. For example, if I run the program and put in 0.35, when it gets to this part
Code:
dimes = (money / 0.1)
, I know money is equal to 0.1 at that point, but dimes is not being set equal to 1. I put in
Code:
std::cout << money;
just to make sure that money equals 0.1 at that point, which it does. I also tried
Code:
std::cout << (money / 0.1)
to see that money, when it is 0.1, divided by 0.1 does indeed equal 1, which it does. But it won't set dimes equal to 1. If I run the program at 0.36, it calculates everything right. What am I doing wrong?