用C++栈实现十进制转2进制
时间: 2024-05-02 07:22:22 浏览: 6
这是一个比较常见的问题,可以采用“除2取余”的方法来实现。具体步骤如下:
1. 定义一个栈用于保存余数。
2. 循环进行以下操作,直到十进制数为0:
a. 将十进制数除以2,得到商和余数。
b. 将余数压入栈中。
c. 将商作为新的十进制数。
3. 循环结束后,依次从栈中取出元素,得到的即为二进制数。
下面是具体的 C 代码实现:
```
#include <stdio.h>
#include <stdlib.h>
#define STACK_SIZE 32
typedef struct {
int top;
int data[STACK_SIZE];
} Stack;
void init_stack(Stack *s)
{
s->top = -1;
}
void push(Stack *s, int value)
{
if (s->top < STACK_SIZE - 1) {
s->data[++s->top] = value;
} else {
printf("Stack is full!\n");
exit(EXIT_FAILURE);
}
}
int pop(Stack *s)
{
if (s->top >= 0) {
return s->data[s->top--];
} else {
printf("Stack is empty!\n");
exit(EXIT_FAILURE);
}
}
int main()
{
int decimal, quotient, remainder;
Stack s;
printf("Please enter a decimal number: ");
scanf("%d", &decimal);
init_stack(&s);
quotient = decimal;
while (quotient != 0) {
remainder = quotient % 2;
push(&s, remainder);
quotient /= 2;
}
printf("The binary equivalent of %d is ", decimal);
while (s.top >= 0) {
printf("%d", pop(&s));
}
printf("\n");
return 0;
}
```