Integers don't take decimals. So when you set:
int quarters = .25
, you are really setting it to 0 because the last bit is truncated (as per the warning you are probably getting). If you say
amount * .25
you are dividing by 4 and then you lose the remainder.
Instead of using
double
as suggested above. I suggest using
int
s so you can take advantage of integer division which would be useful here.
Convert a dollar decimal value to an integer "cents" value by multiplying by 100. Also, instead of using
remaining
,
remaining1
,
remaining2
, just use the
%=
operator to reduce the value by the amount that you are allocating to a higher denomination.
Finally, rename amount, amount1 and amount2. These are not descriptive and will confuse you when you look at this later. Just call them quarters, dimes and nickels. I see that you already have something with that name, but you don't do anything with them, so just delete them.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
int main()
{
float dollars;
cout << "Enter an amount to divide (eg. 13.75)" << endl;
cin >> dollars; //Get your change value
int cents = dollars*100; //Convert it to an integer number of cents.
// int cents = (int)(dollars * 100.); <-- same as line above, but no warning!
int twenties = cents / 2000; // Integer division (how many times can cents be divided by 2000?)
cents = cents % 2000; // Modulus (if I divide cents/2000, what will my remainder be? Set my new value to that)
int tens = cents / 1000; //Now cents is lower than 2000, how many 10s can we get with it?
cents %= 1000; // This is the same as cents = cents % 1000;
int fives = cents / 500;
cents %= 500;
int ones = cents / 100;
cents %= 100;
int quarters = cents / 25;
cents %= 25;
int dimes = cents / 10;
cents %= 10;
int nickles = cents / 5;
cents %= 5;
int pennies = cents; // What's left over!
cout << dollars << "\t Dollars becomes:" << endl;
cout << twenties << "\tTwenties" << endl;
cout << tens << "\tTens" << endl;
cout << fives << "\tFives" << endl;
cout << ones << "\tOnes" << endl;
cout << quarters << "\tQuarters" << endl;
cout << dimes << "\tDimes" << endl;
cout << nickles << "\tNickels" << endl;
cout << pennies << "\tPennies\n" << endl;
cin.get();
return 0;
}
|