c语言代码实现将x的二进制形式存储在栈中
时间: 2023-06-01 20:03:18 浏览: 55
这里给出一个简单的C语言程序,可以将一个整数x的二进制形式存储在栈中:
```c
#include <stdio.h>
#include <stdlib.h>
#define MAX_SIZE 32 // 假设整数是32位
typedef struct {
int top;
int data[MAX_SIZE];
} Stack;
void init(Stack *s) {
s->top = -1;
}
void push(Stack *s, int x) {
if (s->top == MAX_SIZE - 1) {
printf("Stack is full.\n");
exit(1);
}
s->top++;
s->data[s->top] = x;
}
int pop(Stack *s) {
if (s->top == -1) {
printf("Stack is empty.\n");
exit(1);
}
int x = s->data[s->top];
s->top--;
return x;
}
void print_binary(Stack *s) {
printf("Binary representation: ");
while (s->top >= 0) {
printf("%d", pop(s));
}
printf("\n");
}
int main() {
int x;
printf("Enter an integer: ");
scanf("%d", &x);
Stack s;
init(&s);
while (x > 0) {
int bit = x % 2;
push(&s, bit);
x /= 2;
}
print_binary(&s);
return 0;
}
```
这个程序的思路很简单,就是通过不断取余和除以2的方式,把整数x转化为二进制形式,并将每一位(0或1)压入栈中。最后再从栈中依次弹出每一位,并输出即可。
相关推荐
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)