进制转换

来源:互联网 发布:java构造方法的特点 编辑:程序博客网 时间:2024/05/23 22:28

最近学到栈这块内容,自写了一个二进制转八进制的C++实现代码,最近代码写的太少,手有些生了,代码质量明显下降了~

文件一  进制转换.cpp

#include "stack.h"#include <cmath>//二进制转八进制int _tmain(int argc, _TCHAR* argv[]){Stack Binary;//创建二进制栈char c='a';//用于接受二进制字符cin.tie(&cout);cout<<"请输入所需转换的二进制数以#号键结束"<<endl;do{cin>>c;if(c=='0'||c=='1')Binary.Push (c);}while(c!='#');Stack  Hex;Status jugement=OK;//用于返回栈的状态while(jugement ){char sum=0;//储存八进制的每一位数for(int i=0;i<3;i++){if(Binary .EmptyIf ())break;elsesum=sum+(Binary .Pop ()-48)*pow(2,i);}Hex.Push (sum);if(Binary.EmptyIf ())jugement =ERROR;}while(!Hex.EmptyIf ())cout<<(int)Hex.Pop ();cout<<endl;return 0;}
文件二  stack.h

#include <iostream>#include <string>#include <cstdlib>#ifndef STACK_H#define STACK_H#define STACKSIZE 100#define OK 1#define ERROR 0using namespace std;typedef char ElemType;typedef int Status;class Stack{public://复制控制成员Stack(size_t n=0);Stack(Stack &one);~Stack();//出栈入栈基本操作void Push(ElemType &one);ElemType Pop();void DestroyStack();//操作符重载Stack& operator=(Stack&one);ElemType *GetTop()const;ElemType *GetBottom()const ;size_t GetSize()const ;Status EmptyIf();private:size_t size;//栈的深度ElemType *top;//栈顶指针ElemType *bottom;//栈底指针};#endif
文件三 stack.cpp

#include "stack.h"Stack::Stack (size_t n):size(n){bottom=new ElemType [STACKSIZE ];if(!bottom)exit(1);ElemType *p=bottom;for(size_t i=0;i<n;i++,p++){*p=' ';}top=p;}Stack::Stack (Stack&one){if(!bottom)DestroyStack ();bottom=new ElemType [STACKSIZE ];if(!bottom)exit(1);top=bottom;size=0;if(one.EmptyIf() )return;ElemType *p1=bottom,*p2=one.GetBottom ();for(;p2!=one.GetTop ();p1++,p2++){*p1=*p2;}top=p1;}Stack ::~Stack(){DestroyStack ();}void Stack::Push(ElemType &one){if(size>=STACKSIZE ){cout<<"栈已满"<<endl;exit(0);}*(top++)=one;size++;}ElemType Stack::Pop (){if(size<=0){cout<<"已越栈底!"<<endl;exit(0);}size--;return *(--top);}void Stack::DestroyStack (){delete []bottom;top=bottom=NULL;}ElemType *Stack::GetTop()const{return top;}ElemType *Stack::GetBottom ()const{return bottom;}size_t Stack::GetSize ()const{return size;}Status Stack::EmptyIf (){if(size<=0)return OK;else return ERROR ;}

这次遇到问题主要有以下几个:

1.在while,if等引导的语句如果有一行以上都要用{}将代码块包起来。

如:

if(size>=STACKSIZE )cout<<"栈已满"<<endl;exit(0);

这种情况在vs2012中会默认将exit(0)作为if语句块以外的步骤单独运行。

2.选择预编译头文件头后,项目中每个源文件都要添加#include “stdafx.h”,详细参考http://blog.csdn.net/hotandhot/article/details/1346195