Advertisement
chozoii

makeChange

Apr 19th, 2011
170
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.13 KB | None | 0 0
  1. #include<iostream>
  2. #include<string>
  3.  
  4. using namespace std;
  5.  
  6. int makeChange(float total, float paid)
  7. {
  8.     float denom[] = {.01, .05, .10, .25, 1, 5, 10, 20};
  9.     string denomStr[2][8] = {
  10.         { "penny", "nickel", "dime", "quarter", "single", "five", "ten", "twenty" },
  11.         { "pennies", "nickels", "dimes", "quarters", "singles", "fives", "tens", "twenties" },
  12.     };
  13.     float change = paid - total;
  14.  
  15.     cout.precision(2);
  16.  
  17.     if (change < 0)
  18.     {
  19.         cout << "You don't have enough to purchase this item." << endl;
  20.         return -1;
  21.     }
  22.     else if (change == 0)
  23.     {
  24.         cout << "No change given." << endl;
  25.         return 0;
  26.     }
  27.     else
  28.         cout << fixed << total << " from " << paid << " returns:" << endl;
  29.  
  30.     // main algorithm:
  31.     int d, i = 7;
  32.     while (i >= 0)
  33.     {
  34.         if (change >= denom[i])
  35.         {
  36.             d = 0;
  37.             while (change >= denom[i])
  38.             {
  39.                 change = change - denom[i];
  40.                 d++;
  41.             }
  42.             if (d == 1)
  43.                 cout << d << " x " << denomStr[0][i] << endl;
  44.             else
  45.                 cout << d << " x " << denomStr[1][i] << endl; //plurals
  46.         }
  47.         i--;
  48.     }
  49.     return 0;
  50. }
  51.  
  52. int main()
  53. {
  54.     makeChange(3.21, 5.00);
  55.     makeChange(5.00, 3.21);
  56.     makeChange(19.74, 20.00);
  57.  
  58.     return 0;
  59. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement