实现十进制到十六进制的转换

目标是将十进制转化为十六进制,可以用取余法转化和栈的特性得到

分成以下几步

首先我们需要创建一个空栈

typedef struct {
    int *base;
    int *top;
    int stacksize;
} stack;
//定义栈的数据类型

stack s;

void initstack() {
    s.base = (int *)malloc(STACK_INIT_SIZE * sizeof(int));
    s.top = s.base;
    s.stacksize = 100;
}
//创建空栈

然后让用户输入十进制的数字,求余后将余数入栈(这里就出现了第二个函数,入栈)

void push(int e) {
    *s.top++ = e;//将e压入栈顶后更新栈顶指针
}
//入栈操作

在求余结束所有的余数都入栈后,根据栈先进后出的特性,我们只要依次拿出余数就能得到十六进制(也就是出栈函数)

int pop() {
    int e;
    e = *--s.top;//先移动指针,然后将指针所指的元素弹出
    return e;//返回弹出值
}
//出栈操作

接下来便是数据转换

在拿出数据后1-9的值我们可以直接按顺序输出,10-16我们需要先转换为A-E再进行输出

    while (s.top != s.base) {
        a = pop();//将出栈的值赋值给a
        if (a <= 9)
            printf("%d", a);//分情况转换
        else
            printf("%c", a + 55);
    

可以通过这个函数实现

最后加一点进行函数调用

#include 
#include 

#define STACK_INIT_SIZE 100

typedef struct {
    int *base;
    int *top;
    int stacksize;
} stack;
//定义栈的数据类型

stack s;

void initstack() {
    s.base = (int *)malloc(STACK_INIT_SIZE * sizeof(int));
    s.top = s.base;
    s.stacksize = 100;
}
//创建空栈
void push(int e) {
    *s.top++ = e;//将e压入栈顶后更新栈顶指针
}
//入栈操作

int pop() {
    int e;
    e = *--s.top;//先移动指针,然后将指针所指的元素弹出
    return e;//返回弹出值
}
//出栈操作

void conversion() {
    int n;
    int a;
    printf("请输入10进制的数字:\n");
    scanf("%d", &n);//将需要转换的赋值给n
    while (n) {
        push(n % 16);//将n除以16取余,余数入栈
        n = n / 16;
    }
    printf("\n转化为16进制后为:\n");
    while (s.top != s.base) {
        a = pop();//将出栈的值赋值给a
        if (a <= 9)
            printf("%d", a);//分情况转换
        else
            printf("%c", a + 55);
    }
}
//进制转换的函数
int main() {
    initstack();
    conversion();
    return 0;
}

完成了

你可能感兴趣的:(算法,c#)