【问题标题】:Binary to Decimal using Stack in C二进制到十进制在C中使用堆栈
【发布时间】:2021-03-21 13:19:22
【问题描述】:

在 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!");
    }
}

【问题讨论】:

  • 如果您的代码正在运行并且您希望得到反馈,那么在Code Review 发帖会更合适。
  • 另外,请注意 C 和 C++ 是不同的语言,因此您应该只引用和标记您实际需要编码的语言。这很重要,因为这两种语言的最佳实现可能不同。
  • @kaylum 感谢您的建议,我会进行更改。谢谢你帮助我。这是我在 stackoverflow 上的第一篇文章。
  • 是否有理由将二进制字符串读取为十进制数?通过这样做,您最多只能使用 1023 个数字(明白为什么?)。更方便的方法是读取一串数字。那么十进制除法/模数将是不必要的。堆栈也不是很有用。
  • 不是优化建议,但是滥用全局变量很可怕。

标签: c binary stack decimal


【解决方案1】:

建议:

  • 读取一串二进制数字:这在转换为 32 位无符号整数时最多允许 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;
}

【讨论】:

    猜你喜欢
    • 2015-01-28
    • 2018-04-21
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    • 2021-06-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多