Experiment 2: Convert Decimal to Binary

algorithm:

Step 1: Enter num,m,i;

The second step, num%2 , get the quotient m and the remainder i;

The third step, if num%2 is not equal to 0 , then num=m, m%2, output i, otherwise,

Output the binary value.

Source code:

# include<iostream>

using namespace std;

const int StackSize=100;

template <class DataType>

class SeqStack

{

    

public:

SeqStack(){top=-1;}

~SeqStack(){}

void Push(DataType x);

DataType Pop();

DataType GetTop();

int Empty();

private:

DataType data[StackSize];

int top;

};

template <class DataType>

void SeqStack<DataType>::Push(DataType x)

{

if(top==StackSize-1) throw"上溢";

top++;

data[top]=x;

}

template <class DataType>

DataType SeqStack<DataType>::Pop()

{

DataType x;

if(top==-1) throw"下溢";

x=data[top--];

return x;

}

template <class DataType>

DataType SeqStack<DataType>::GetTop()

{

if(top!=-1) return data[top];

}

template <class DataType>

int SeqStack<DataType>::Empty()

{

if(top==-1) return 1;

else return 0;

}

void transform(int n,int b)  

{

SeqStack<int> S;

    int i;  

    while(n)  

    {  

        S.Push(n%b);

        n=n/b;  

    }  

    while(!S.Empty())

    {  

        i=S.GetTop();

        S.Pop();

        cout<<i;  

    }  

}  

intmain()  

{  

     int num, d=2;

    cout<<"Input the num:";  

    cin>>num;

    transform(num,d);  

    system("pause");  

    return 0;  

}  

Program result:

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324730931&siteId=291194637