我正在用 C 编写一个 PIC18F252 微 Controller 。该程序应该从传感器获取 3 个独立输入(首先通过 ADC),然后根据这 3 个输入的组合,它将从 switch 语句中选择一个输出。 因此,例如,如果每个传感器输出一个 0,我想选择案例“000”并执行其指令。如果中间的传感器输出 1,我想要 case 010 等。
我研究过使用数组或字符串来存储 3 个字符的值,但我似乎无法正确使用 switch 语句来比较输入与大小写。
似乎 if/else 语句是一种更简单的方法,但我需要使用 switch。
那么谁能告诉我是否可以将数组或字符串与大小写进行比较,或者是否有任何其他方法可以做到这一点?我能想到的唯一其他方法是将输入组合分配给一个单词变量,但这需要一个 switch 或它自己的 if/else 语句。
最佳答案
如果输入值是数字值(0 或 1),您可以通过位移和按位或将这些位组合成一个数字。
例子:
int input1 = 0;
int input2 = 1;
int input3 = 1;
int combined;
/* assuming the values can be 0 or 1 only */
combined = input1 | ( input2 << 1 ) | ( input3 << 2 );
/* or with any non-zero value as TRUE */
combined = (input1 ? 1 << 0 : 0) | (input2 ? 1 << 1 : 0) | ( input3 ? 1 << 2 : 0);
switch(combined)
{
case 0x0: // or GCC extension 0xb000
case 0x1: // or GCC extension 0xb001
case 0x2: // or GCC extension 0xb010
case 0x3: // or GCC extension 0xb011
/* ... */
}
关于c - 您将如何使用带有 3 个二进制输入组合的 switch 语句? (C),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58558063/