读书人

进制转换无法实现求原因,该如何处理

发布时间: 2012-04-23 13:17:38 作者: rapoo

进制转换无法实现,求原因
#define OVERFLOW 0;
#define OK 1;
#define ERROR 0;
#define STACK_INIT_SIZE 100;
#define STACKINCREMENT 10;
typedef char SElemType;
typedef struct{
SElemType *base;
SElemType *top;
int stacksize;
}SqStack;
int InitStack(SqStack &S);
int Push(SqStack &S,SElemType e);
int Pop(SqStack &S,SElemType &e);
int StackEmpty(SqStack S);
void conversion();


#include "1.h"
#include<malloc.h>
#include<stdio.h>
#include<stdlib.h>
int InitStack(SqStack &S){
S.base=(SElemType *)malloc(STACK_INIT_SIZE * sizeof(SElemType));
if(!S.base) exit (OVERFLOW);
S.top=S.base;
S.stacksize=STACK_INIT_SIZE;
return OK;
}//构造空栈
int Push(SqStack &S,SElemType e)
{
if(S.top-S.base>=S.stacksize)
{S.base=(SElemType *)realloc(S.base,S.stacksize+STACKINCREMENT)*sizeof(SElemType));
if(!S.base)exit(OVERFLOW);
S.top=S.base+S.stacksize;
S.stacksize+=STACKINCREMENT;
}
*S.top++=e;
return OK;
}//进栈
int Pop(SqStack &S,SElemType &e){
if(S.top==S.base)return ERROR:
e=*--S.top;
return OK;
}//出栈
int StackEmpty(SqStack S)
{if(S.top==S.base)
return 1;
else
return 0;
}
void conversion()
{ SqStack S;
SElemType e;
int N;
if(!InitStack(S))
exit(OVERFLOW);
printf("请输入一个十进制数:");
scanf("%d",&N);
while (N)
{
Push(S,N%16);
N=N/16;
}
while(!StackEmpty(S))
{
Pop(S,e);
printf("%d",e);
}
}

#include"1.h"
void main()
{
conversion();
}



[解决办法]
宏定义的后面不要加分号
另外,N%16入栈的时候,要注意区分0-9和A-F
[解决办法]
你要的是16进制的转换吧
C/C++
//数值转换
#include"stdio.h"
#include"stdlib.h"
#include"string.h"
#define ElemType int
#define STACK_INIT_SIZE 100
typedef struct
{
ElemType *base;
ElemType *top;
ElemType stacksize;
}SqStack;


void InitStack(SqStack *s)
{
s->base = (ElemType *)malloc(STACK_INIT_SIZE *sizeof(ElemType));
if (!s->base)
printf("分配内存失败\n");

s->top = s->base;
s->stacksize = STACK_INIT_SIZE;
}

int push(SqStack *s, int e)
{

if (s->top - s->base >= s->stacksize)
{
printf("栈满了\n");
}
else
{
*(s->top) = e;
s->top++;
}

return 0;
}

int StackEmpty(SqStack *s)
{
if (s->top > s->base)
return 1;
else
return 0;

}

int Pop(SqStack *s, int e)
{
if (s->top < s->base)
return 0;
else
{
s->top --;
e = *s->top;
switch(e)
{
case 10:printf("A");break;
case 11:printf("B");break;
case 12:printf("C");break;
case 13:printf("D");break;
case 14:printf("E");break;
case 15:printf("F");break;
default:printf("%d",e);break;
}
}
return 1;
}

int main()
{
int N,e;
SqStack s;
InitStack(&s);
scanf("%d",&N);
while (N)
{
int t =N%16;
push(&s,t);
N = N/16;


}
while(StackEmpty(&s))
{
Pop(&s,e);
}

return 0;
}
程序还是可以跑的,随便改改也可以变其他进制的了

读书人网 >软件架构设计

热点推荐