代码之家  ›  专栏  ›  技术社区  ›  user3289834

C代码中不使用*运算符而将2位二进制数相乘的一个小错误

  •  -3
  • user3289834  · 技术社区  · 11 年前

    真的需要帮助,因为这个bug很小,几乎没有6-7行代码。。我已经附加了.cpp文件链接,该链接经过了很好的注释,以解释代码中出现的错误 1 [单击她获取代码]。。请帮忙,因为我坚持了一个小时或更长时间。。明天需要提交此iN学院!

    /*Multiplication Of 2-Bit Binary Numbers Without Using Multiplication Operator*/
    
    /*
        1   1
        1   1
        -----
        1   1
    1   1   0
    ---------
    (By Full Adder)
    1   0   0   1
    
    */
    
    #include<stdio.h>
    #include<conio.h>
    
    void main()
    {
    
        int k=0,a[4],b[4],i,x,y,temp=0,temp1=0,temp2=0,ans[2],j=1,c=0,sum=0;
    
        clrscr();
    
        printf("Enter The 2-Bit Binary Number(1):\t");
        scanf("%d",&x);
    
        printf("Enter The 2-Bit Binary Number(2):\t");
        scanf("%d",&y);
    
    
        for(i=10;i<=100;i=i*10)
        {
         temp=y%i;
         temp=temp/(i/10);
    
         if(temp==1)
            {
             ans[j]=x;
            }
    
         else
            {
            ans[j]=0;
            }
    
         j++;
    
        }
    
    
        ans[2]=ans[2]*10;
    
    
        //Implementing Full Adder
    
        for(i=10;i<=10000;i=i*10)
    
            {
    
             //if anyone in comment, correct output
    
             /* considering second commented and input for x and y as 11
                the output for //1 would be
                0
                1
                1
                0
                0
             */  
    
    
            //if both //1 //2 uncommented, wrong output
            /*  0
                1
                0
                1
                0
                0
                0
                0
                0
                0
            */ 
    
    
             // 1
             temp2=ans[2]%i;
             temp2=temp2/(i/10);
             printf("%d\n",temp2);
    
             // 2
             temp1=ans[1]%i;
             temp1=temp1/(i/10);
             printf("%d\n",temp1);
    
    
             sum=(temp1^temp2)^c;
             c=(temp1&temp2)|((temp1^temp2)&c);
    
             b[k]=sum;
             k++;
            }
    
    
        for(i=0;i<4;i++)
        {
         printf("%d",b[i]);
        }
    
    
        getch();
    
    }
    
    1 回复  |  直到 11 年前
        1
  •  0
  •   Mahozi    11 年前
    void main()
    

    应该是

    int main()
    

    main的返回类型为int。

    编辑:

    在分析代码之后,似乎您应该在最后一个循环中以自下而上的顺序执行XOR。基本上,你是在反向打印答案。

    因此:

    for(i=0;i<4;i++)
    

    应该是:

    for(i=3;i>=0;i--)