用顺序栈遍写进制转换 c语言
时间: 2024-06-15 21:07:57 浏览: 54
应用顺序栈,编程实现由十六进制到二进制的转换
用顺序栈实现进制转换的C语言代码如下:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 100
typedef struct {
int data[MAX_SIZE];
int top;
} Stack;
void initStack(Stack *s) {
s->top = -1;
}
int isEmpty(Stack *s) {
return s->top == -1;
}
int isFull(Stack *s) {
return s->top == MAX_SIZE - 1;
}
void push(Stack *s, int value) {
if (isFull(s)) {
printf("Stack is full.\n");
return;
}
s->data[++s->top] = value;
}
int pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty.\n");
return -1;
}
return s->data[s->top--];
}
void convertToBinary(int num) {
Stack s;
initStack(&s);
while (num != 0) {
push(&s, num % 2);
num /= 2;
}
printf("Binary representation: ");
while (!isEmpty(&s)) {
printf("%d", pop(&s));
}
printf("\n");
}
int main() {
int decimalNum;
printf("Enter a decimal number: ");
scanf("%d", &decimalNum);
convertToBinary(decimalNum);
return 0;
}
```
阅读全文