帮我用C语言的栈做一个进制转换器
时间: 2023-05-17 09:07:56 浏览: 84
好的,以下是使用C语言栈实现进制转换的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_STACK_SIZE 100
typedef struct {
int top;
int data[MAX_STACK_SIZE];
} Stack;
void initStack(Stack *s) {
s->top = -1;
}
int isEmpty(Stack *s) {
return s->top == -1;
}
int isFull(Stack *s) {
return s->top == MAX_STACK_SIZE - 1;
}
void push(Stack *s, int x) {
if (isFull(s)) {
printf("Stack is full.\n");
exit(1);
}
s->data[++s->top] = x;
}
int pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty.\n");
exit(1);
}
return s->data[s->top--];
}
int convert(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
} else if (c >= 'a' && c <= 'f') {
return c - 'a' + 10;
} else if (c >= 'A' && c <= 'F') {
return c - 'A' + 10;
} else {
printf("Invalid character: %c\n", c);
exit(1);
}
}
char convertBack(int n) {
if (n >= 0 && n <= 9) {
return n + '0';
} else if (n >= 10 && n <= 15) {
return n - 10 + 'a';
} else {
printf("Invalid number: %d\n", n);
exit(1);
}
}
int main() {
Stack s;
initStack(&s);
char input[100];
int from, to;
printf("Enter a number: ");
scanf("%s", input);
printf("Enter the base of the number: ");
scanf("%d", &from);
printf("Enter the base to convert to: ");
scanf("%d", &to);
int len = strlen(input);
int i;
for (i = 0; i < len; i++) {
int n = convert(input[i]);
push(&s, n);
}
int result = 0;
int power = 1;
while (!isEmpty(&s)) {
int n = pop(&s);
result += n * power;
power *= from;
}
char output[100];
int j = 0;
while (result > 0) {
int n = result % to;
output[j++] = convertBack(n);
result /= to;
}
output[j] = '\0';
printf("Result: %s\n", strrev(output));
return 0;
}
```
这个程序可以将一个任意进制的数转换为另一个任意进制的数。用户需要输入要转换的数、原始进制和目标进制。程序会将输入的数转换为十进制,然后再将十进制数转换为目标进制。
阅读全文