How do I transform an IF statement with 2 variables onto a switch function using C?

前端 未结 7 1903
伪装坚强ぢ
伪装坚强ぢ 2021-01-27 07:49

I have an IF-statement that I want to transform into a Switch-statement... But it has 2 variables! Is it possible to do it on C?

It is a rock, paper, scissors game:

相关标签:
7条回答
  • 2021-01-27 08:33

    In general, the answer is "no": switch statements work with a single variable. However, in some cases you can do the conversion. For example, if you have two variables, a and b, where a can be 0, 1, or 2, and b that can be 0, 1, 2, or 3, you can do a switch like this:

    switch (a*10+b) {
        case  0: break; // a == 0, b == 0
        case 10: break; // a == 1, b == 0
        case 20: break; // a == 2, b == 0
        case  1: break; // a == 0, b == 1
        case 11: break; // a == 1, b == 1
        case 21: break; // a == 2, b == 1
        case  2: break; // a == 0, b == 2
        case 12: break; // a == 1, b == 2
        case 22: break; // a == 2, b == 2
        case  3: break; // a == 0, b == 3
        case 13: break; // a == 1, b == 3
        case 23: break; // a == 2, b == 3
    }
    
    0 讨论(0)
提交回复
热议问题