64,691
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#define STACK_INIT_SIZE 20
#define STACRINCREMENT 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 + STACRINCREMENT) * 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("请输入一个二进制的数,回车结束单前输入:\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);
sum = sum + (c - '0') * pow(2, i);
}
printf("转换为十进制数是:%d\n", sum); /*这儿应该输出sum*/
return 0;
}
以上是修改后的代码,输入格式应该用%;
其他修改之处详见上面的代码;//请今后要用
char c;
scanf("%c",&c);
//时,都改为
char s[2];
char c;
scanf("%1s",s);
c=s[0];
//自动跳过一个或多个空格或Tab字符或回车换行,读取下一个字符。
if ( s->top-s->base ==s->stackSize)
{
}
scanf("%c", &c);
if ( s->top - s->base == s->stackSize)
{
}
scanf("%c", &c);