Lập Trình C/C++ - Decimal To Binary Using Constructor

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

class binaryToDecimal
{
 /* By default private variables */
 int binary;

 public:
  /* Constructor declaration */
  binaryToDecimal(int decimal)
  {
   int i = 1;
   binary = 0;
   while(decimal != 0)
   {
    binary += (decimal % 2) *i;
    i *= 10;
    decimal /= 2;
   }
  }

  /* Function prototype declaration */
  void display();
};

/* Member function definition outside class */
void binaryToDecimal :: display()
{
 /* Access private variable */
 cout << "Binary value is: " << binary << endl;
}

int main()
{
 int decimal;
 cout << "Welcome to Decimal to Binary converter" << endl;
 cout << "Enter a Decimal number:" << endl;
 cin >> decimal;

 /* Constructor called explicitly */
 binaryToDecimal btod = binaryToDecimal(decimal);
 btod.display();
 return 0;
}

0 Comment:

Đăng nhận xét

Thank you for your comments!