C语言顺序栈实现十进制转十六进制
#include <stdio.h> #include <stdlib.h>
typedef int SElemType; // 定义栈元素类型为整型
typedef struct { SElemType* data; // 栈的元素数组指针 int top; // 栈顶指针 int maxSize; // 栈的最大容量 } SqStack;
// 初始化栈 void InitStack(SqStack* s, int maxSize) { s->data = (SElemType*)malloc(sizeof(SElemType) * maxSize); s->top = -1; s->maxSize = maxSize; }
// 入栈 void Push(SqStack* s, SElemType x) { if (s->top == s->maxSize - 1) { return; // 栈满,无法入栈 } s->top++; s->data[s->top] = x; }
// 出栈 SElemType Pop(SqStack* s) { if (s->top == -1) { return -1; // 栈空,无法出栈 } SElemType x = s->data[s->top]; s->top--; return x; }
// 十进制转换为十六进制 void DecimalToHexadecimal(unsigned n) { SqStack s; InitStack(&s, 100);
// 除以16取余数,将余数入栈,直到商为0
while (n != 0) {
Push(&s, n % 16);
n = n / 16;
}
// 出栈并打印每个十六进制数位
while (s.top != -1) {
SElemType x = Pop(&s);
if (x < 10) {
printf('%d', x);
} else {
printf('%c', x - 10 + 'A');
}
}
printf('
'); }
int main() { unsigned n; scanf('%u', &n); DecimalToHexadecimal(n); return 0; }
// 输入: // 10
// 输出: // A
// 解释: // 输入的非负十进制整数为10,将其转换为十六进制数,结果为A。
原文地址: https://www.cveoy.top/t/topic/OGj 著作权归作者所有。请勿转载和采集!