十进制转r进制c语言
时间: 2024-02-05 14:04:53 浏览: 24
以下是一个将十进制数转换为r进制的C语言程序,其中r为进制数,data为待转换的十进制数:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
#define ElemType char
typedef struct {
ElemType *base;
ElemType *top;
int stacksize;
} SqStack;
void InitStack(SqStack &S) {
S.base = (ElemType *)malloc(STACK_INIT_SIZE * sizeof(ElemType));
if (!S.base) exit(0);
S.top = S.base;
S.stacksize = STACK_INIT_SIZE;
}
void Push(SqStack &S, ElemType e) {
if (S.top - S.base >= S.stacksize) {
S.base = (ElemType *)realloc(S.base, (S.stacksize + STACKINCREMENT) * sizeof(ElemType));
if (!S.base) exit(0);
S.top = S.base + S.stacksize;
S.stacksize += STACKINCREMENT;
}
*S.top++ = e;
}
void Pop(SqStack &S, ElemType &e) {
if (S.top == S.base) exit(0);
e = *--S.top;
}
int StackEmpty(SqStack S) {
if (S.top == S.base) return 1;
else return 0;
}
char inttochar(int n) {
if (n >= 0 && n <= 9) return n + '0';
else return n - 10 + 'A';
}
void conversion(int data, int r) {
SqStack S;
InitStack(S);
while (data) {
Push(S, inttochar(data % r));
data = data / r;
}
while (!StackEmpty(S)) {
ElemType e;
Pop(S, e);
printf("%c", e);
}
printf("\n\n");
}
int main() {
int data, r;
printf("请输入待转换的十进制数:");
scanf("%d", &data);
printf("请输入进制数:");
scanf("%d", &r);
printf("转换结果为:");
conversion(data, r);
return 0;
}
```