在C中从if else转换为Switch

0 c switch-statement

在每个人的帮助下,我重新编辑了我的代码.我更新了我的问题:如何使用switch结构增加状态.我将[((button_in&0x0040)!= 0)]表达式放入switch(expr)中.这给了我我想要的前两个州.(1)按下按钮1产生0001.(2)按下按钮2产生0010.我不确定如何编程按下按钮1 TWICE以产生0010.我可以使用正确方向的提示或点.我整天都在研究这个问题,我觉得问题与交换机的表达有关.谢谢

int main()
{
char state;
char A;
int button_in = 0; 
DeviceInit();   //set LED1 thru LED4 as digital output
DelayInit();    //Initialize timer for delay

while(1)
{
button_in = PORTReadBits (IOPORT_A, BIT_6 | BIT_7);
if (button_in != 0)
{
    switch ((button_in & 0x0040) != 0)
    {
    case 0: ((button_in & 0x0040) != 0);  //1. Press button1. State goes to 001.
                 PORTWrite (IOPORT_B, BIT_11);
                 break;

    default: //((button_in & 0x0080) != 0); //2. Press button2. State goes to 010
                 PORTWrite (IOPORT_B, BIT_10);
                 break;
    }

    DelayMs(100);
    PORTClearBits(IOPORT_B, BIT_10 | BIT_11 | BIT_12 | BIT_13);
    //Add Breakpoint here
}
}
}
Run Code Online (Sandbox Code Playgroud)

wal*_*lyk 6

代码具有格式错误的switch语句.写这样:

int main()
{
    char state;
    int button_in = 0;
    DeviceInit();
    DelayInit();

    button_in = PORTReadBits (IOPORT_A, BIT_6 | BIT_7);
    if (button_in != 0)
    {
        switch (state)
        {
        case 'A': if ((button_in & 0x0040) != 0)  //1. Press button1. State goes to 001.
                     PORTWrite(IOPORT_B, BIT_10);
                  break;
        case 'B': if ((button_in & 0x0080) != 0) //1aaab. Press button2. State goes to 1000
                    PORTWrite (IOPORT_B, BIT_13);
                  break;
        }

        DelayMs(100);
        PORTCLearBits(IOPORT_B, BIT_10 | BIT_11 | BIT_12 | BIT_13);
        //Add Breakpoint here
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 注意`state`在`switch(state)`中使用之前没有初始化也没有分配. (3认同)