十进制转化为二进制C语言代码
时间: 2023-08-18 21:00:31 浏览: 111
以下是利用栈将十进制整数转化为二进制数的C语言代码:
```
#include <stdio.h>
#include <stdlib.h>
#define STACK_SIZE 100
typedef struct {
int top;
int data[STACK_SIZE];
} Stack;
void initStack(Stack *s) {
s->top = -1;
}
int isEmpty(Stack *s) {
return s->top == -1;
}
int isFull(Stack *s) {
return s->top == STACK_SIZE - 1;
}
void push(Stack *s, int x) {
if (isFull(s)) {
printf("Stack overflow\n");
exit(1);
}
s->data[++s->top] = x;
}
int pop(Stack *s) {
if (isEmpty(s)) {
printf("Stack underflow\n");
exit(1);
}
return s->data[s->top--];
}
void decimalToBinary(int n) {
Stack s;
initStack(&s);
while (n > ) {
push(&s, n % 2);
n /= 2;
}
while (!isEmpty(&s)) {
printf("%d", pop(&s));
}
}
int main() {
int n;
printf("Enter a decimal number: ");
scanf("%d", &n);
printf("Binary equivalent: ");
decimalToBinary(n);
printf("\n");
return ;
}
```
阅读全文