(利用栈实现)输入一个十进制正整数,输出其八进制数和十六进制数

2024-11-12 11:42:24
推荐回答(4个)
回答1:

#include
#include
#define maxsize 50

typedef int elemtype;

typedef struct
{
elemtype data[50];
int top;
}sqstack; /*顺序栈类型定义*/

void initstack(sqstack *s) /*建立空栈*/
{
s=(sqstack *)malloc(sizeof(sqstack));
s->top=-1;
}

int stacklength(sqstack *s) /*求栈长*/
{
return (s->top+1);
}

elemtype gettop(sqstack *s)/*取栈顶元素*/
{
elemtype x;
if(s->top==-1) return 0;
x=s->data[s->top];
return x;
}

int push(sqstack *s,elemtype x)/*在栈顶插入新元素*/
{
s->top++;
s->data[s->top]=x;
return 1;
}

int pop(sqstack *s)/*删除栈顶元素*/
{
if(s->top==-1) return 0;
else s->top--;
return 1;
}

int stackempty(sqstack *s)/*判断栈是否为空*/
{
if(s->top==-1) return 1;
else return 0;
}

void visit(sqstack *s)
{
int i;
elemtype x;
i=s->top;
while(i!=-1)
{x=s->data[i];
printf("%3d",x);
i--;
}

printf("\n");
}

void clearstack(sqstack *s)
{
s->top=-1;
}

void convert(int n,int e) /*将十进制数n转换成e进制数并输出*/
{
int i;
sqstack *s;
initstack(s);
while(n)
{
i=n%e;
n=n/e;
push(s,i);
}
printf("the number after conversion:\n");
while(!stackempty(s))
{
printf("%d",gettop(s));
pop(s);
}
}

void main()
{
int i,j;
clrscr();
printf("Enter the number you want to convert:");
scanf("%d",&i);

printf("Enter the hexadecimal :");
scanf("%d",&j);

convert(i,j);
getch();
}

回答2:

#include
#define MAXSIZE 1024 栈可能达到的最大容量
typedef int DataType;
typedef struct
{ DataType data[MAXSIZE];
int top;
}SeqStack;SeqStack *initSeqStack() 栈初始化
{ SeqStack *s;
s=(SeqStack*)malloc(sizeof(SeqStack));
s->top=-1;
return s;
}
int empty(SeqStack *s) 判栈空
{ if(s->top==-1)
return 1;
else
return 0;
}
int push(SeqStack *s,DataType x)入栈
{ if(s->top==MAXSIZE-1)
{ printf("overflow");
return 0;
}
s->top++;
s->data[s->top]=x;
return 1;
}
void pop(SeqStack *s) 出栈
{ s->top--;
}
DataType top(SeqStack *s) 读栈
{ return (s->data[s->top]);
}
void convert(int N,int r,int m) 转换进制运算
{ SeqStack *s;

int x;
char c;
s=ininSeqStack();

while(N)
{ push(s,N%r);
N=N/r;
}
while(!empty(s))
{ x=top(s);
pop(s);
printf("%d",x);

}
s=top;
free(s);
return top;
while(N)
{push(s,N%m);
N=N/m;
}
while(!empty(s))
{ x=top(s);
pop(s);
if (x<10)
c=y+48;
else
c=y-10+'A';
printf("%c",c);

} }
int main()
{ SeqStack *SeqS;
int N,r,m;
int x;
printf("Please Enter a number: ");
scanf("%d",&N);
r=8;
m=16;
SeqS=initSeqStack();
empty(SeqS);
x=10;
pop(SeqS);
top(SeqS);
pop(SeqS);
convert(N,r,m);
getch();
}

回答3:

int *Init()
{
int *top,*base;
base=(int *)malloc(sizeof(int) * 50);
if(!base) {printf("Error!");exit();}
top=base;
return top;
} int *push(int *top,int n)
{
*top=n;
top++;
return top;
} int pop(int *top)
{
int e;
top--;
e=*top;
return e;
} void convs()
{
int *top, *base;
int e,N;
int i;
top=Init();
base=top;
printf("Input the number:\n");
scanf("%d",&N);
while(N!=0)
{
top=push(top,N%8);
N=N/8;
}
printf("After change,the number is:\n");
while(top!=base)
{
e=pop(top);
top--;
printf("%d",e);
}
printf("\n");
}
main()
{
convs();
getch();
} 哈哈,搞笑,培基

回答4:

培基,你好厉害哦!