Lập Trình C/C++ - Count Number of Coins/Notes with Destructor

#Code:
#include<iostream>
using namespace std;

class counter
{
 int thousand, fivehundred, hundred, fifty, twenty, ten, five, two, one, remaining;

 public:
  /* Constructor prototype declaration */
  counter(int);
  
  void display()
  {
   cout << "Number of Coins/Notes" << endl;
   cout << "Thousand - " << thousand << endl;
   cout << "Five Hundred - " << fivehundred << endl;
   cout << "Hundred - " << hundred << endl;
   cout << "Fifty - " << fifty << endl;
   cout << "Twenty - " << twenty << endl;
   cout << "Ten - " << ten << endl;
   cout << "Five - " << five << endl;
   cout << "Two - " << two << endl;
   cout << "One - " << one << endl;
  }

  /* Destructor for class 'counter' */
  ~counter()
  {
   cout << "Object of the class destroyed!"  << endl;
  }
};

/* Constructor definition outside class */
counter :: counter(int amount)
{
 thousand = fivehundred = hundred = fifty = twenty = ten = five = two = one = remaining = 0;

 thousand = amount / 1000;
 remaining = amount - thousand * 1000;

 fivehundred = remaining / 500;
 remaining -= fivehundred * 500;

 hundred = remaining / 100;
 remaining -= hundred * 100;

 fifty = remaining / 50;
 remaining -= fifty * 50;

 twenty = remaining / 20;
 remaining -= twenty * 20;

 ten = remaining / 10;
 remaining -= ten * 10;

 five = remaining / 5;
 remaining -= five * 5;

 two = remaining / 2;
 remaining -= two * 2;

 one = remaining;
}


int main()
{
 int amount;
 cout << "Enter your amount to count Coins/Notes:" <<  endl;
 cin >> amount;
 
 /* Constructor called explicitly */
 counter ctr = counter(amount);
 ctr.display();
 return 0;
}

0 Comment:

Đăng nhận xét

Thank you for your comments!