简体   繁体   English

使用数组和堆栈的十进制到二进制转换

[英]Decimal To Binary conversion using Array and Stack

This is the C Program I have written to convert a Decimal number to it's equivalent Binary number.这是我编写的 C 程序,用于将十进制数转换为等效的二进制数。 I have used Stack (implemented using array) and the following algorithm:我使用了 Stack(使用数组实现)和以下算法:

Number is divided and remainders are pushed in stack.数字被除,余数压入堆栈。 Remainders are popped one at a time and converted into Binary剩余部分一次弹出并转换为二进制

The Problem is that the program works fine for numbers up to 3, after that from 4 on wards, each Binary Number comes one less than the actual number.问题是该程序对于最多 3 的数字可以正常工作,之后从 4 到病房,每个二进制数都比实际数字少 1。

// Decimal to Binary conversion using Stack
#include<stdio.h> 
#include<math.h>

#define max 20

int top=-1, stk[max];
void push(int);
int pop(void);

int main() 
{
     int i,num,x,flag=0,s, bin=0, factor;
     printf("Enter any decimal number: ");
     scanf("%d",&num);
     while(num>0)
     {
         if(num==1)
             push(num);
         else
         {
             x = num%2;
             push(x);
          }
         num/=2;
         flag++;
     }

for(i=0;i<flag;i++)
{
    s = pop();
    bin = bin + s*pow(10,(flag-1-i));
}

printf("\nEquivalent Binary number is --> %d",bin);
return 0;
}

void push(int n)
{
     if(top == max-1)
     {
          printf("Error! Overflow");
          return;
     }
     stk[++top] = n;
 }

 int pop(void)
 {
     int y;
     if(top == -1)
     {
          printf("Error! Underflow");
          return;
     }
     y = stk[top];
     top = top-1;
     return y;
  }

Will anybody help me by finding the logical flaw?有人会通过找到逻辑缺陷来帮助我吗?

Thank You谢谢你

函数 pow 返回一个可以有 9999999... 小数点后的双精度值,当它被转换为 int 时四舍五入到地板,您可以使用 ceil() 函数解决您的问题,该函数返回最小的整数值比或等于参数,像这样。

bin = bin + ceil(s*pow(10,(flag-1-i)));

My answer is your program is unnecessarily complicated.我的回答是你的程序不必要地复杂。

#include<stdio.h> 

int main() 
{
    unsigned num, i, zeros = 0;
    printf("Enter a decimal number: ");
    scanf("%u", &num);
    printf ("Decimal %u in binary is ", num);
    for (i=sizeof(unsigned)*8; i>0; i--)
    {
        if ((int)num < 0)           // get MSB
            zeros = printf ("1");   // cancel 0-suppresion
        else if (zeros)
            printf ("0");
        num <<= 1;
    }
    printf ("\n");
    return 0;
}
 //C Program to convert Decimal to binary using Stack

 #include<stdio.h>

 #define max 100

 int stack[max],top=-1,i,x;

         /*------ Function Prototype------------*/
  void push (int x)
  {
    ++top;
    stack [top] = x;

   }
  int pop ()
   {
    return stack[top];

   }

          /*-------------------------------------*/
  void  main()
  {
    int num, total = 0,item;
    printf( "Please enter a decimal: ");
    scanf("%d",&num);

    while(num > 0)
     {
       total = num % 2;
       push(total);
       num /= 2;
     }

    for(i=top;top>-1;top--)
    {
     item = pop ();
     printf("%d",item);
    }
  }

Here is a simpler version of your above program这是上述程序的更简单版本

    int main(){
    int n,remainder;
    printf("Enter a decimal number:");
    scanf("%d",&n);
    while(n!=0){
        remainder = n%2;
        n = n/2;
        push(remainder); // inserting in stack
    }
    display(); // displaying the stack elements
}

reference of above code C program to Convert Decimal number into Binary using Stack上面代码C程序的参考使用堆栈将十进制数转换为二进制数

So I've done the math on several numbers, and this appears to be correct.所以我已经对几个数字进行了数学计算,这似乎是正确的。 I would agree with others that this is needlessly complicated, but that is not causing your issues on it's own, it's just making them harder to find.我会同意其他人的看法,即这不必要地复杂化,但这并不会导致您的问题本身,而只是让它们更难找到。

So the output of this program appears correct, from a logical standpoint.所以从逻辑的角度来看,这个程序的输出看起来是正确的。 Lets look into other potential issues:让我们看看其他潜在的问题:

  1. You're indexing an array with an int that you initialize to -1您正在使用初始化为 -1 的 int 索引数组
  • This is bad practice, and unnecessary.这是不好的做法,也是不必要的。 Array indexes in C can never be negative, so the compiler will assume this is an unsigned number, so if you have a 32 bit processor, it will assume you're trying to get array[2^32 - 1], which is not what you want. C 中的数组索引永远不会是负数,因此编译器会假设这是一个无符号数,因此如果您有一个 32 位处理器,它会假设您正在尝试获取数组 [2^32 - 1],这不是你想要什么。 Always use a unsigned value for array indexes始终对数组索引使用无符号值

  • What MIGHT be happening, and I'm not certain, is that your compiler is doing something with this behind the scenes which is screwing up your program, it's really hard to say.可能会发生什么,我不确定,是你的编译器在幕后做了一些事情,这会搞砸你的程序,这真的很难说。 But it's probably attempting to convert your negative number into an unsigned int before you do your addition.但它可能试图在您进行加法之前将您的负数转换为 unsigned int。 Fix this by changing your declaration of top to:通过将 top 的声明更改为:

    unsigned int top = 0;无符号整数顶部 = 0;

and changing where you access top from:并更改您访问 top 的位置:

 stk[++top] = n;

to

 stk[top++] = n;

You will also have to change你也将不得不改变

 y = stk[top];
 top = top-1;

to

 top = top-1;
 y = stk[top];

I'd say start there.我会说从那里开始。 I'd also suggest removing the pow line, and just individually printing each piece of the array, because it will output in the same way, and you already have all the info there ie.我还建议删除 pow 线,并单独打印数组的每一部分,因为它将以相同的方式输出,并且您已经拥有所有信息,即。

PRINTF("%d%d%d",stk[2],stk[1],stk[0]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM