#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int top;
} SeqStack;
void InitStack(SeqStack *s) {
s->top = -1;
}
bool StackEmpty(SeqStack *s) {
return s->top == -1;
}
bool Push(SeqStack *s, int e) {
if (s->top == MAX_SIZE - 1) {
return false;
}
s->data[++s->top] = e;
return true;
}
bool Pop(SeqStack *s, int *e) {
if (StackEmpty(s)) {
return false;
}
*e = s->data[s->top--];
return true;
}
void DecimalToBaseM(int decimal, int base, char *result) {
SeqStack s;
InitStack(&s);
int remainder;
while (decimal > 0) {
remainder = decimal % base;
Push(&s, remainder);
decimal /= base;
}
int index = 0;
while (!StackEmpty(&s)) {
Pop(&s, &remainder);
if (remainder < 10) {
result[index++] = '0' + remainder;
} else {
result[index++] = 'A' + (remainder - 10);
}
}
result[index] = '\0';
for (int i = 0; i < index / 2; i++) {
char temp = result[i];
result[i] = result[index - 1 - i];
result[index - 1 - i] = temp;
}
}
int main() {
int decimal, base;
char result[MAX_SIZE];
printf("请输入一个十进制整数: ");
scanf("%d", &decimal);
printf("请输入转换的进制数m (2-16): ");
scanf("%d", &base);
if (base < 2 || base > 16) {
printf("进制数必须在2到16之间。\n");
return 1;
}
DecimalToBaseM(decimal, base, result);
printf("转换后的%d进制数为: %s\n", base, result);
return 0;
}