【发布时间】: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 个数字(明白为什么?)。更方便的方法是读取一串数字。那么十进制除法/模数将是不必要的。堆栈也不是很有用。
-
不是优化建议,但是滥用全局变量很可怕。