用c语言用栈写二进制转换为十进制
时间: 2023-05-21 15:01:50 浏览: 142
以下是用 C 语言使用栈实现二进制转十进制的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_SIZE 100
typedef struct {
int top;
int data[MAX_SIZE];
} Stack;
void init(Stack *s) {
s->top = -1;
}
int is_empty(Stack *s) {
return s->top == -1;
}
int is_full(Stack *s) {
return s->top == MAX_SIZE - 1;
}
void push(Stack *s, int value) {
if (is_full(s)) {
printf("Stack is full.\n");
exit(1);
}
s->data[++s->top] = value;
}
int pop(Stack *s) {
if (is_empty(s)) {
printf("Stack is empty.\n");
exit(1);
}
return s->data[s->top--];
}
int main() {
char binary[MAX_SIZE];
printf("Enter a binary number: ");
scanf("%s", binary);
Stack s;
init(&s);
int len = strlen(binary);
for (int i = 0; i < len; i++) {
int bit = binary[i] - '0';
push(&s, bit);
}
int decimal = 0;
int base = 1;
while (!is_empty(&s)) {
int bit = pop(&s);
decimal += bit * base;
base *= 2;
}
printf("Decimal equivalent: %d\n", decimal);
return 0;
}
```
如果您有任何问题,请随时问我。
阅读全文