进制转换

来源:互联网 发布:mac不能拷贝文件到u盘 编辑:程序博客网 时间:2024/05/16 05:27

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
typedef int DataType;
typedef struct stacknode {
DataType data;
struct stacknode * next;
}StackNode;

typedef struct {
StackNode * top;
}LinkStack;

//错误信息
Error (char * message)
{
printf ("Erroe:%s",message);
exit (1);
}

//初始化链栈
void InitStack (LinkStack * s)
{
s->top = NULL;
}
//判栈空
int StackEmpty (LinkStack * s)
{
return s->top == NULL;
}
//入栈
void Push (LinkStack * s , DataType x)
{
StackNode * p = (StackNode * ) malloc (sizeof(StackNode));
p->data = x;
p->next = s->top;
s->top = p;
}
//出栈
DataType Pop(LinkStack *s)
{
DataType x;
StackNode * p = s->top;
if ( StackEmpty (s))
   Error ("下溢");
x = p->data;
s->top = p->next;
free (p);
return x;
}
//取栈顶
DataType StackTop (LinkStack* s)
{
if (StackEmpty (s))
   Error ("栈为空");
return s->top->data;
}
//数值转换
void MultiBaseOutput (int N,int B)
{
int i;
LinkStack s;
InitStack (&s);
while (N){
   Push (&s,N%B);
   N=N/B;
}
while (! StackEmpty(&s)){
   i=Pop (&s);
   printf ("%d",i);
}
}
void main()
{
int N,B,i;
char ch = 'N';
i=1;
while (ch!='q') {

while (i){
   printf ("请输入要转换的正整数:");
   scanf ("%d",&N);
   fflush(stdin);
   if ((int)N!=N||N<=0)
    printf ("请输入正整数!/n");
   else
    i=0;
}
i=1;
while (i){
   printf ("请输转换的进制:");
   scanf ("%d",&B);
   fflush(stdin);
   if ((int)B!=B||B<=1)
    printf ("请输入大于0的正整数!/n");
   else
   i = 0;
}
i = 1;
printf ("%d的%d进制为:",N,B);
MultiBaseOutput (N,B);
N=B=0;
printf ("/n任意键继续,q退出");
ch = getchar();
fflush(stdin);
system("cls");
}
}

原创粉丝点击