我有一个多路复用器的功能。
// Enumerated type for a single bit.
typedef enum { FALSE=0, TRUE=1 } BIT;
BIT multi(BIT A, BIT B, BIT C, BIT D, BIT S1, BIT S0)
{
    if(S1== FALSE && S0 ==FALSE)
        return A;
    else if(S1==FALSE && S0==TRUE)            
        return B;
    else if (S1== TRUE && S0== FALSE)
        return C;
    else
        return D;
}
对于多路复用器,S1、S0 为两位二进制数,按给定顺序索引到 A、B、C、D。
因此,S1==0 & S0==0 指的是 A,S1==0 & S0==1 指的是 B 等等。
我觉得我的代码很接近或很遥远,或者它是正确的,我只需要修复我在 main 中测试它的方式,其中我有......
 assert(multiplexer(FALSE, FALSE, FALSE, FALSE, FALSE, FALSE) == A);
 assert(multiplexer(TRUE, TRUE, TRUE, TRUE, TRUE, TRUE) == D);
这两个测试并不是精心设计的。我们以第一个为例(更改为 的实际函数名称multi):
assert(multi(FALSE, FALSE, FALSE, FALSE, FALSE, FALSE) == A);
在这种情况下multi()应该返回第一个参数,但是你怎么知道它是否返回了其他三个参数中的一个,因为它们都是假的。此外,我不确定该D变量是否在函数外部可用,因此我切换到更具体的值。
所以更好的测试集是:
assert(multi(FALSE, TRUE,  TRUE,  TRUE,  FALSE, FALSE) == FALSE);
assert(multi(TRUE,  FALSE, FALSE, FALSE, FALSE, FALSE) == TRUE);
这是为了测试 的返回A。对于B,C只需D将唯一值移动到正确的位置(分别为 2、3 或 4),然后更改作为选择器传递的内容(位置 5 和 6)。
同样,对于第二个,您需要重新编写测试,以便可以区分成功和失败:
assert(multi(FALSE, FALSE, FALSE, TRUE, TRUE, TRUE) == TRUE);
assert(multi(TRUE,  TRUE,  TRUE, FALSE, TRUE, TRUE) == FALSE);
顺便说一句,我不确定为 C 本身已经可以很好处理的类型创建特殊枚举(布尔值作为int)是否有用。
在我看来,代码可以大大简化为:
int multi (int r0, int r1, int r2, int r3, int s0, int s1) {
    if (s0) {
        // Must be r2 or r3, depending on s1.
        if (s1) return r3;
        return r2;
    }
    // s0 is false, must be r0 or r1, depending on s1.
    if (s1) return r1;
    return r0;
}
或者,一旦你真正理解了 C :-)
// Returns rX based on sX:
//   s0 false, s1 false, return r0.
//   s0 false, s1 true,  return r1.
//   s0 true,  s1 false, return r2.
//   s0 true,  s1 true,  return r3.
int multi (int r0, int r1, int r2, int r3, int s0, int s1) {
    return ((s0) ? ((s1) ? r3 : r2) : ((s1) ? r1 : r0));
}