用c语言用栈写一个将十进制转换为二进制
时间: 2024-05-13 22:15:31 浏览: 9
好的,这里是用栈实现将十进制转换为二进制的C语言代码,主要是利用栈后进先出的特点,将余数一一入栈,最后出栈输出即可。
```c
#include <stdio.h>
#define MAX_SIZE 100
int stack[MAX_SIZE];
int top = -1;
// 入栈
void push(int num) {
top++;
stack[top] = num;
}
// 出栈
int pop() {
int num = stack[top];
top--;
return num;
}
// 判断栈是否为空
int is_empty() {
return top == -1;
}
int main() {
int num;
printf("请输入一个十进制数:");
scanf("%d", &num);
// 将余数入栈
while (num) {
push(num % 2);
num /= 2;
}
// 出栈并输出
printf("转换为二进制为:");
while (!is_empty()) {
printf("%d", pop());
}
return 0;
}
```
运行结果:
```
请输入一个十进制数:10
转换为二进制为:1010
```
相关问题
用C语言栈写一个十进制转换二进制的代码
好的,以下是一个用C语言栈写的十进制转换二进制的代码:
```C
#include <stdio.h>
#include <stdlib.h>
#define STACK_SIZE 20
struct stack {
int top;
int items[STACK_SIZE];
};
void push(struct stack *s, int x) {
if (s->top == STACK_SIZE-1) {
printf("Stack overflow\n");
exit(EXIT_FAILURE);
}
s->items[++(s->top)] = x;
}
int pop(struct stack *s) {
if (s->top == -1) {
printf("Stack underflow\n");
exit(EXIT_FAILURE);
}
return s->items[(s->top)--];
}
void decimal_to_binary(int n) {
struct stack s;
s.top = -1;
while (n > 0) {
int rem = n % 2;
push(&s, rem);
n = n / 2;
}
printf("Binary number is: ");
while (s.top != -1) {
printf("%d", pop(&s));
}
printf("\n");
}
int main() {
int n;
printf("Enter a decimal number: ");
scanf("%d", &n);
decimal_to_binary(n);
return 0;
}
```
该程序使用了一个栈来存储每个二进制位。在进行转换时,将给定的十进制数除以2,将余数压入栈中,直到得到的商为0。然后从栈中弹出每个元素并打印出来,这样就可以得到该十进制数的二进制表示。
用c语言栈写一个二进制转换十进制的程序
好的,以下是一个用 C 语言栈实现二进制转换为十进制的程序:
```c
#include <stdio.h>
#define MAX_SIZE 100
// 栈的结构体定义
struct Stack {
int top;
int arr[MAX_SIZE];
};
// 初始化栈
void initStack(struct Stack *s) {
s->top = -1;
}
// 判断栈是否已满
int isFull(struct Stack *s) {
return s->top == MAX_SIZE - 1;
}
// 判断栈是否为空
int isEmpty(struct Stack *s) {
return s->top == -1;
}
// 入栈操作
void push(struct Stack *s, int item) {
if (isFull(s)) {
printf("Stack is full\n");
return;
}
s->arr[++s->top] = item;
}
// 出栈操作
int pop(struct Stack *s) {
if (isEmpty(s)) {
printf("Stack is empty\n");
return -1;
}
return s->arr[s->top--];
}
// 二进制转换为十进制
int binaryToDecimal(char binary[]) {
struct Stack s;
initStack(&s);
int i = 0, decimal = 0, power = 1;
// 将二进制数的每一位依次入栈
while (binary[i] != '\0') {
push(&s, binary[i] - '0');
i++;
}
// 依次出栈并计算十进制数
while (!isEmpty(&s)) {
decimal += pop(&s) * power;
power *= 2;
}
return decimal;
}
int main() {
char binary[MAX_SIZE];
printf("Enter a binary number: ");
scanf("%s", binary);
int decimal = binaryToDecimal(binary);
printf("Decimal equivalent of %s is %d\n", binary, decimal);
return 0;
}
```
程序通过栈的数据结构来实现二进制转换为十进制,`push` 函数用来入栈,`pop` 函数用来出栈,`binaryToDecimal` 函数用来将二进制数转换为十进制数。在 `main` 函数中,读取用户输入的二进制数,并调用 `binaryToDecimal` 函数来计算十进制数的值,最后输出结果。