二进制转换为8进制,#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define STACK_INIT_SIZE 20
#define STACKINCREMENT 10 //追加的空间大小
typedef char ElemType;
typedef struct
{
ElemType *base; //栈底
ElemType *top; //栈顶
int stackSize; //栈的容量
}sqStack;
void InitStack(sqStack *s)
{
s->base=(ElemType *)malloc(STACK_INIT_SIZE*sizeof(ElemType));
if(*s->base)
{
exit(0);
}
s->top=s->base;
s->stackSize=STACK_INIT_SIZE; //栈的容量
}
void Push(sqStack *s, ElemType e) //入栈
{
//如果栈满, 追加空间
if(s->top-s->base >= s->stackSize)
{
s->base=(ElemType *)realloc(s->base,(s->stackSize+STACKINCREMENT)*sizeof(ElemType));
//realloc 追缴空间的函数
if(!s->base)
exit(0);
s->top=s->base+s->stackSize;
s->stackSize=s->stackSize+STACKINCREMENT;
}
*(s->top)=e;
s->top++;
}
void Pop(sqStack *s, ElemType *e) //出栈
{
if(s->top==s->base)
return;
*e= *--(s->top);
}
void ClearStack(sqStack *s) //清空栈
{
s->top=s->base;
}
void DestroyStack(sqStack *s) //销毁栈
{
int i, len;
len=s->stackSize;
for(i=0;i<len ;i++)
{
free(s->base);
s->base++;
}
s->base= s->top= NULL;
s->stackSize = 0;
}
int StackLen(sqStack s) //计算栈的当前容量
{
return(s.top-s.base);
}
int main()
{
ElemType c, c1='0';
sqStack s, s1 ;
int len , len1, i ,j=0;
InitStack(&s);
InitStack(&s1);
printf("请输入二进制数,输入#符号表示结束!\n");
scanf("%c",&c);
while(c!='#')
{
Push(&s, c);
scanf("%c",&c);
}
getchar(); //清理键盘缓冲区, 清空#
len= StackLen(s);
printf("栈的当前容量是%d\n", len);
for(i=0;i<len; i++)
{
Pop(&s, &c);
c1=c1+(c-48)*pow(2,j);
j++;
if(j==3)
{
Push(&s1, c1);
j=0;
c1='0';
}
}
if(i==len&&j!=3)
{
Push(&s1, c1);
}
len1= StackLen(s1);
printf("新栈的当前容量是%d\n", len1);
printf("转换为八进制数是:");
for(i=0;i<len1;i++)
{
Pop(&s1, &c);
printf("%c", c);
}
printf("\n");
return 0;
}
|