用c语言将一个十进制正整数转换为r进制数,并输出转换后的值,用链栈实现
时间: 2024-02-24 13:59:28 浏览: 66
以下是使用链栈实现将一个十进制正整数转换为r进制数的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链栈节点结构体
typedef struct node {
int data;
struct node *next;
} Node, *LinkStack;
// 初始化链栈
LinkStack initStack() {
LinkStack top = (LinkStack)malloc(sizeof(Node));
top->next = NULL;
return top;
}
// 判断链栈是否为空
int isEmpty(LinkStack top) {
return top->next == NULL;
}
// 入栈
void push(LinkStack top, int data) {
Node *newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = top->next;
top->next = newNode;
}
// 出栈
int pop(LinkStack top) {
if (isEmpty(top)) {
printf("Stack is empty.");
return -1;
}
Node *p = top->next;
int data = p->data;
top->next = p->next;
free(p);
return data;
}
// 十进制正整数转换为r进制数
void decimalToR(int decimal_number, int r) {
LinkStack stack = initStack();
while (decimal_number != 0) {
push(stack, decimal_number % r);
decimal_number = decimal_number / r;
}
while (!isEmpty(stack)) {
printf("%d", pop(stack));
}
}
int main() {
int decimal_number = 123;
int r = 16;
printf("%d in base %d is ", decimal_number, r);
decimalToR(decimal_number, r);
printf(" in base %d", r);
return 0;
}
```
输出结果为:
```
123 in base 16 is 7B in base 16
```
阅读全文