当然可以。以下是将给定的 Python 代码翻译成 C 语言的版本,实现了相同的功能:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct Stack {
char *data;
int top;
int capacity;
} Stack;
Stack *create_stack(int capacity) {
Stack *stack = (Stack *)malloc(sizeof(Stack));
stack->data = (char *)malloc(capacity * sizeof(char));
stack->top = -1;
stack->capacity = capacity;
return stack;
}
void push(Stack *stack, char value) {
if (stack->top == stack->capacity - 1) {
stack->capacity *= 2;
stack->data = (char *)realloc(stack->data, stack->capacity * sizeof(char));
}
stack->data[++stack->top] = value;
}
char pop(Stack *stack) {
return stack->data[stack->top--];
}
int is_empty(Stack *stack) {
return stack->top == -1;
}
void jinzhizhuanhua(int num, int fundamention, Stack *stack) {
const char *dic = "0123456789ABCDEF";
if (num < fundamention) {
push(stack, dic[num]);
} else {
push(stack, dic[num % fundamention]);
jinzhizhuanhua(num / fundamention, fundamention, stack);
}
}
int main() {
Stack *stack = create_stack(10);
jinzhizhuanhua(22543253, 16, stack);
while (!is_empty(stack)) {
printf("%c", pop(stack));
}
printf("\
");
free(stack->data);
free(stack);
return 0;
}
这段 C 代码实现了一个简单的栈结构,并使用递归函数 jinzhizhuanhua 将给定的十进制数转换为指定进制。在这个例子中,我们将 22543253 转换为十六进制。
请注意,本回答来自GPT-4
如果问题已经解决,请设置最佳答案 |