实验3.5 十进制转换

来源:互联网 发布:python网络编程 amazon 编辑:程序博客网 时间:2024/05/01 11:05

一、实验目的

1、   熟练掌栈和队列的结构特点,掌握栈和队列的顺序存储和链式存储结构和实现。

2、   学会使用栈和队列解决实际问题。

二、实验内容

    设计算法并写出代码,实现一个十将二进制转换成2进制数。

三、实验源代码
#include <iostream>  using namespace std;    const int StackSize=100;  template<class DataType>  class SeqStack  {      public:          SeqStack();          ~SeqStack(){};          void Push(DataType x);          DataType Pop();          void Decimaltor(int num,int r);      private:          DataType data[StackSize];          int top;  };  template<class DataType>  SeqStack<DataType>::SeqStack()  {      top=-1;  }  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>  void SeqStack<DataType>::Decimaltor(int num,int r)  {      int k;      top=-1;      while(num!=0)      {          k=num%r;//得到余数           Push(k);          num=num/r;      }      while(top!=-1){          cout<<Pop();      }        }    int main()  {      int num;      int r;      SeqStack<int>S;      cout<<"请输入一个十进制的数字:";      cin>>num;      cout<<"请问你要转换为几进制:";      cin>>r; cout<<"转换后的"<<r<<"进制数字为:";    S.Decimaltor(num,r);  cout<<endl;    return 0;  }   


四、实验结果截图




原创粉丝点击