fork download
  1. #include <algorithm>
  2. #include <cstdlib>
  3. #include <ctime>
  4. #include <functional>
  5. #include <iostream>
  6. #include <iomanip>
  7. #include <string>
  8. #include <utility>
  9. #include <vector>
  10.  
  11. struct coin
  12. {
  13. coin(std::string name_, int value_) : value(value_), name(name_) {}
  14. unsigned value;
  15. std::string name;
  16. };
  17.  
  18. bool operator<(const coin& lhs, const coin& rhs)
  19. {
  20. return lhs.value < rhs.value;
  21. }
  22.  
  23. int main()
  24. {
  25. std::vector<std::pair<coin, int>> money = { //Coin data and amount
  26. {{"Quarter", 25}, 0}, {{"Dime", 10}, 0}, {{"Nickel", 5}, 0}, {{"Penny", 1}, 0}
  27. };
  28. std::sort(money.begin(), money.end(), std::greater<std::pair<coin, int>>());
  29.  
  30. srand(time(nullptr));
  31. unsigned change = rand() % 100;
  32.  
  33. std::cout << std::fixed << std::setprecision(2);
  34. std::cout << "Change Due: $" << (change / 100.0) << "\n";
  35. std::cout << "Coin Dispenser will dispense:\n";
  36. if (change == 0) {
  37. std::cout << "No Coins\n";
  38. return 0;
  39. }
  40. for(auto& data: money) {
  41. data.second = change / data.first.value;
  42. change %= data.first.value;
  43. }
  44. for(const auto& data: money) {
  45. if (data.second != 0)
  46. std::cout << std::left << std::setw(11) <<
  47. (" " + data.first.name + ":") << data.second <<
  48. " ($" << (data.second * data.first.value / 100.0) << ")\n";
  49. }
  50. }
  51.  
Success #stdin #stdout 0s 3480KB
stdin
Standard input is empty
stdout
Change Due:   $0.42
Coin Dispenser will dispense:
 Quarter:  1 ($0.25)
 Dime:     1 ($0.10)
 Nickel:   1 ($0.05)
 Penny:    2 ($0.02)