簡體   English   中英

二進制到十進制使用 C 中的堆棧

[英]Binary to Decimal using Stack in C

使用 C 中的堆棧將二進制轉換為十進制的代碼。 我已經使用堆棧來存儲轉換后的總和,並且只從包含總和的堆棧中彈出頂部元素。 請提出任何優化建議。

#include<stdio.h>
#include<conio.h>
#define MAX 100
int stack[MAX];
int top=-1;
int num;
void push();
void pop();
main()
{
    printf("Enter the binary number: ");
    scanf("%d",&num);
    push();
    pop();
}
void push()
{
    int rem;
    
        int dec_value = 0;
        int base = 1;
        int temp = num;
        while(temp)
        {
            int last_digit = temp % 10;
            temp = temp / 10;
            dec_value += last_digit * base;
            base = base * 2;
                
        if(top>=MAX)
        {
            printf("\nSTACK OVERFLOW!");
        }
        else
        {
            top++;
            stack[top]=dec_value;
        }
    }
}
void pop()
{
    int i;
    printf("Its decimal form: ");
    printf("%d",stack[top]);
    if(top<0)
    {
        printf("\nStack is empty!");
    }
}

建議:

  • 讀取一串二進制數字:這在轉換為 32 位無符號 integer 時最多允許 32 個二進制數字,而不是讀取 int 時只有 10 個二進制數字。
  • 在沒有堆棧的情況下進行轉換:您只需要在循環字符串時進行移位。

這是一種可能性。 請注意,輸入未經過徹底檢查。

#include <stdio.h>
#include <inttypes.h>

#define N 33

int main(void) {
    char bits[N];
    char *c;
    uint32_t n = 0;
    
    fgets(bits, N, stdin);
    for (c = &bits[0]; *c != '\n' && *c != 0; c++) {
        n = (n << 1) | (*c == '1');
    }
    printf("%u\n", n);
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM