//c语言描述 将2进制转化为10进制
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define STACK_INIT_SIZE 20
#define //栈满后再分配 typedef char ElemType;
typedef struct
{
ElemType *base; //栈底
ElemType *top; //栈底
int stackSize; // 栈的容量
}sqStack; void InitStack (sqStack *s) //初始化栈
{
s -> base = (ElemType*) malloc(STACK_INIT_SIZE);
if(! s-> base)
{
printf("分配空间失败");
exit();
}
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)
{
printf("分配空间失败");
exit();
}
}
*(s->top) = e; //先赋值
s->top++; //指针在+1
} void Pop(sqStack * s,ElemType *e) //出栈
{
if(s->top == s->base )
{
printf("栈为空,没法出栈");
return;
}
*e = *--(s->top); //首先把s->top的元素赋值给e 再将地址--
} int StackLen (sqStack s) //返回栈有多少个元素
{
return ( s.top - s.base); // 实质是地址相减 除以ElemType
} int main()
{
ElemType c; //声明一个字符c
sqStack s; //声明一个结构体s int len,i,sum=;
InitStack(&s); //初始化栈
printf("请输入二进制数,输入#结束!\n");
scanf("%c",&c);
while( c != '#')
{
Push (&s,c);
scanf ("%c",&c);
}
getchar(); //接收回车键
len =StackLen(s);
printf("栈的当容量:%d\n",len);
for(i=; i<len ; i++)
{
Pop(&s,&c);
sum = sum + (c-) * pow(,i);
}
printf("转化为十进制数为:%d \n",sum); return ;
}