#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));
if(!s->base)
{
exit(0);
}
}
*(s->top) = e;
s->top++;
}
void Pop(sqStack *s,ElemType *e)//弹出
{
if( s->top == s->base)
{
return;
}
*e= *--(s->top);
}
int StackLen(sqStack s)
{
return (s.top - s.base);
}
int main()
{
ElemType c;
sqStack s;
int len,i,sum = 0;
InitStack(&s);
printf("输入二进制数,以!为结尾标志:");
scanf("%c",&c);
while(c!='!')
{
Push(&s,c);
scanf("%c",&c);
}
len = StackLen(s);
printf("栈的当前容量是%d\n",len);
for(i = 0;i < len;i++)
{
Pop(&s,&c);
sum = sum + (c-48) * pow(2,i);//pow函数
}
printf("转化为十进制数是:%d\n",sum);
return 0;
}
二进制转化十进制(栈的应用)
最新推荐文章于 2024-01-14 16:54:00 发布