首页 > 应用开发 > C/C++ > 设计一个十进制转化为随意进制的程序
#include<stdio.h>
#include<stdlib.h>
#define SIZE 20
#define MORE 10
typedef struct{
int *base;
int top;
int stacksize;
}SqStack;
void InitStack(SqStack &S)//构造一个空栈
{
S.base=(int *)malloc(SIZE*sizeof(int));
if(!S.base) return ;
S.top=0;
S.stacksize=SIZE;
}
int StackEmpty(SqStack &S)//判空 是返回1 否返回0
{
if(S.top==0) return 1;
else return 0;
}
void Push(SqStack &S,int e)//入栈
{
if(S.top>=S.stacksize)
{
S.base=(int *)realloc(S.base,(S.stacksize+MORE)*sizeof(int));
if(!S.base) exit(0);
S.stacksize+=MORE;
}
S.base[S.top++]=e;
}
void Pop(SqStack &S,int &e)//出栈
{
if(S.top==0) exit(0);
else
e=S.base[--S.top];
}
void GetTop(SqStack &S,int &e)//取栈顶元素
{
if(S.top==0) exit(0);
else
e=S.base[S.top-1];
}
void Res(SqStack &S,int n,int d)//将10进制数n转换为d进制
{
InitStack(S);
while(n)
{
Push(S,n%d);
n=n/d;
}
}
int main()
{
while (1)
{
int n, d, e;
SqStack S;
printf("******************************\n");
printf("* 输入要转换的10进制数: *\n");
printf("******************************\n");
scanf("%d", &n);
printf("******************************\n");
printf("* 请输入转换进制: *\n");
printf("******************************\n");
printf("* 请选择一个你要转换的进制 *\n");
printf("* 2-任意进制 *\n");
printf("******************************\n");
scanf("%d", &d);
Res(S, n, d);
printf("******************************\n");
printf("* 输出结果: *\n");
printf("******************************\n");
while (!StackEmpty(S))
{
Pop(S, e);
printf("%d", e);
}
printf("\n");
printf("******************************\n");
printf("******************************\n");
system("pause");
printf("******************************\n");
}
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/70007056/viewspace-2793754/ ,如需转载,请注明出处,否则将追究法律责任。