c语言利用顺序栈将输入的非负的十进制数N转换为指定的d(二、八或十六)进制数。
时间: 2023-05-25 16:04:38 浏览: 161
以下是使用顺序栈将十进制数转换为二进制、八进制或十六进制数的C语言代码:
#include <stdio.h>
#include <stdlib.h>
//定义栈的结构体
typedef struct
{
int top; //栈顶指针
int maxSize; //栈的最大容量
int* stack; //栈的指针
} Stack;
//初始化栈
void init(Stack* s, int maxSize)
{
s->top = -1;
s->maxSize = maxSize;
s->stack = (int*)malloc(maxSize * sizeof(int));
}
//判断栈是否为空
int isEmpty(Stack* s)
{
return (s->top == -1);
}
//判断栈是否已满
int isFull(Stack* s)
{
return (s->top == s->maxSize - 1);
}
//入栈
void push(Stack* s, int x)
{
if (!isFull(s))
s->stack[++s->top] = x;
}
//出栈
int pop(Stack* s)
{
if (!isEmpty(s))
return s->stack[s->top--];
}
//将十进制数转换为指定进制数
void convert(int N, int d)
{
Stack s;
init(&s, 100);
while (N != 0)
{
push(&s, N % d);
N /= d;
}
while (!isEmpty(&s))
{
int digit = pop(&s);
if (digit < 10)
printf("%d", digit);
else
printf("%c", 'A' + digit - 10); //输出十六进制时,将10~15转换为A~F
}
printf("\n");
}
int main(void)
{
int N, d;
printf("Input a non-negative decimal number: ");
scanf("%d", &N);
printf("Input the base of target number system(2, 8, or 16): ");
scanf("%d", &d);
printf("The result is: ");
convert(N, d);
return 0;
}
阅读全文