343 views

用栈实现进制转换

堆栈应用之进制转换

最近数据结构开始接触链表,堆栈,队列等,刚开始觉得好无聊,它们差不多,也没什么用处,,,不过今天看到了几个堆栈的应用,还挺有意思的…

C语言代码如下:

#include<stdio.h>
#include<stdlib.h>

typedef struct
{
    int data[100];
    int top;
}sqstack;

sqstack stack;

void initstack()
{
    stack.top = -1;
}

void push(int n)
{
    if(stack.top >= 99)
    {
       printf("超出转换范围\n");
       exit(-1);
    }
    else
    {
       stack.top++;
       stack.data[stack.top] = n;
    }
}

int pop()
{
    if (stack.top != -1)
    {
       int temp = stack.data[stack.top];
       stack.top-;
       return temp;
    }
    else
    {
       printf("出现错误");
       exit(-1);
    }
}

void conversion()
{
    int n,e,m;
    initstack();
    printf("输入要转换的数\n");
    scanf("%d",&n);
    printf("要转化几进制\n");
    scanf("%d",&m);
    while(n)
    {
        push(n%m);
        n=n/m;   
    }
   
    while(stack.top>=0)
    {
        e=pop();
        printf("%d",e);
    }
}

int main(int argc, char **argv)
{
    conversion();
    return 0;
}

无觅相关文章插件,快速提升流量

One thought on “用栈实现进制转换

  1. 如果数字的长度超过30,也就是超过unsigned long int的最大值,该怎么做?

发表评论

电子邮件地址不会被公开。 必填项已用 * 标注

*

您可以使用这些 HTML 标签和属性: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>