二进制加法器只在*大部分*时间工作

Binary adder only working *most* of the time

我目前正在研究二进制加法器。

寄存器A、B为输入寄存器。它们存储为双向链表。寄存器 S 用于输出。 (为了真相table)

这里是真相table提供:

一个 |乙 |进位 |年代 |结转

0 | 0 | 0 | 0 | 0

0 | 0 | 1 | 1 | 0

0 | 1 | 0 | 1 | 0

0 | 1 | 1 | 0 | 1

1 | 0 | 0 | 1 | 0

1 | 0 | 1 | 0 | 1

1 | 1 | 0 | 0 | 1

1 | 1 | 1 | 1 | 1

这是保存指向它们的指针以及其他数据的结构 (CPU):

struct cpu_t
{
        int word_size; 
        int unsign; 
        int overflow; 
        int carry;
        int sign;
        int parity;
        int zero;
        struct bit_t *r1_head;
        struct bit_t *r1_tail;
        struct bit_t *r2_head;
        struct bit_t *r2_tail;
        struct bit_t *r3_head;
        struct bit_t *r3_tail;
};

这是我的添加函数:

void add_function(struct cpu_t *cpu)
{
    int i = 0;

    struct bit_t *temp1 = cpu->r1_tail;
    struct bit_t *temp2 = cpu->r2_tail;
    struct bit_t *temp3 = cpu->r3_tail;

    while(i < (cpu->word_size))
    {
        if(temp1->n == 0 && temp2->n == 0 && cpu->carry == 0)
        {
            temp3->n = 0;   
            cpu->carry = 0;
        }
        else if(temp1->n == 0 && temp2->n == 0 && cpu->carry == 1)
        {
            temp3->n = 1;   
            cpu->carry = 0;
        }
        else if(temp1->n == 0 && temp2->n == 1 && cpu->carry == 0)
        {
            temp3->n = 1;   
            cpu->carry = 0;
        }
        else if(temp1->n == 0 && temp2->n == 1 && cpu->carry == 1)
        {
            temp3->n = 0;   
            cpu->carry = 1;
        }
        else if(temp1->n == 1 && temp2->n == 0 && cpu->carry == 0)
        {
            temp3->n = 1;   
            cpu->carry = 0;
        }
        else if(temp1->n == 1 && temp2->n == 0 && cpu->carry == 1)
        {
            temp3->n = 0;   
            cpu->carry = 1;
        }
        else if(temp1->n == 1 && temp2->n == 1 && cpu->carry == 0)
        {
            temp3->n = 0;   
            cpu->carry = 1;
        }
        else if(temp1->n == 1 && temp2->n == 1 && cpu->carry == 1)
        {
            temp3->n = 1;   
            cpu->carry = 1;
        }

        temp1 = temp1->prev;
        temp2 = temp2->prev;
        temp3 = temp3->prev;
        i++;
    }
}

下面是一些示例输出,显示了我遇到的问题类型:

word_size 为 2:

01 + 01 = 10(正确)

word_size 为 4:

0111 + 0001 = 1001(错误)

word_size 为 8:

10101010 + 01010101 = 11111111(正确)

11101101 + 01101000 = 01010110(不正确,实际是01010101)

word_size 为 4:

1001 + 0110 = 1111(正确)

1111 + 1111 = 1110(正确)

那么,基于此输入,有人知道为什么我的代码不起作用吗?有什么想法吗?

如果您需要我编辑更多代码,我想我可以轻松做到。如果没有,我会通过评论告诉你你需要什么。

感谢您的帮助!

OP 的测试用例期望 cpu->carry 在执行 void add_function(struct cpu_t *cpu) 时有一个 0。

看起来 OP 应该有 2 个添加功能并相应地使用。

void addc_function(struct cpu_t *cpu) {
  // existing code 
}

void add_function(struct cpu_t *cpu) {
  cpu->carry = 0;
  addc_function(cpu);
}