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

前端 未结 7 1976
伪装坚强ぢ
伪装坚强ぢ 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:11

    The too-clever-by-half solution:

    enum Play { Rock = 0, Paper = 1, Scissors = 2 };
    enum Outcome { Tie = 0, P1Win = 1, P2Win = 2 };
    
    enum Play parseMove(char input) {
        switch (input) {
            case 'R': return Rock;
            case 'P': return Paper;
            case 'S': return Scissors;
            default: /* invalid input */;
        }
    }
    
    enum Outcome gameResult(enum Play p1, enum Play p2) {
        return (3 + p1 - p2)%3;
    }
    
    ...
    
    switch(gameResult(parseMove(play1), parseMove(play2))) {
        case Tie: printf("Tie!\n");
        case P1Win: printf("Player 1 wins!\n");
        case P2Win: printf("Player 2 wins!\n");
    }
    

提交回复
热议问题