除了if else之外的决策代码

时间:2014-04-11 20:40:31

标签: c++ operators conditional-statements

我想知道是否有人可以帮我理解一些代码。它是一个tic tac toe程序..

我有一段代码没有得到,但似乎允许系统区分两种选择。 我常常说这样的话。

cout<<"enter choice.1 or 2";
cin>>choice;

但是在这段代码中他们有

player=(player%2)?1:2;

和这个

mark=(player == 1) ? 'X' : 'O';

完整代码

char square[10] = {'o','1','2','3','4','5','6','7','8','9'};
int checkwin();
void board();

int main()
{
    int player = 1,i,choice;
    char mark;
    clrscr();
    do
    {
        board();
        player=(player%2)?1:2; //<<--- This part I don't understand
        cout << "Player " << player << ", enter a number:  ";
        cin >> choice;
        mark=(player == 1) ? 'X' : 'O'; //<<--- This part I don't understand
        if (choice == 1 && square[1] == '1')
            square[1] = mark;
        else if (choice == 2 && square[2] == '2')
            square[2] = mark;
        else if (choice == 3 && square[3] == '3')
            square[3] = mark;
        else if (choice == 4 && square[4] == '4')
            square[4] = mark;
        else if (choice == 5 && square[5] == '5')
            square[5] = mark;
        else if (choice == 6 && square[6] == '6')
            square[6] = mark;
        else if (choice == 7 && square[7] == '7')
            square[7] = mark;
        else if (choice == 8 && square[8] == '8')
            square[8] = mark;
        else if (choice == 9 && square[9] == '9')
            square[9] = mark;
        else
        {
            cout<<"Invalid move ";
            player--;
            getch();
        }
        i=checkwin();
        player++;
    }while(i==-1);
    board();
    if(i==1)
        cout<<"==>\aPlayer "<<--player<<" win ";
    else
        cout<<"==>\aGame draw";
    getch();
    return 0;

4 个答案:

答案 0 :(得分:3)

这是conditional operator

mark = (player == 1) ? 'X' : 'O';

相当于

if(player == 1)
{
   mark = 'X';
}
else
{
   mark = 'O';
}

答案 1 :(得分:1)

作业:

var  =  cond ? x : y;

与:

相同
if (cond) {
    var = x;
} else {
    var = y;
}

答案 2 :(得分:0)

答案 3 :(得分:0)

player=(player%2)?1:2; //<<--- This part I don't understand

%是模数运算符,它在分割后有效地取余数:(How does the modulus operator work?

当你拿(玩家%2)时,不同玩家值的结果将是:

player(1) -> 1
player(2) -> 0
player(3) -> 1
player(4) -> 0
...

然后他们将此结果转换为真实的玩家编号:

player = result ? 1 : 2;

如果玩家是1,3,5,结果将是1非零(真)...在这种情况下,他们将玩家重新定义为1.如果玩家是2,4,6,......那么他们将玩家重新定义为2。

这是一种强制执行玩家总是1或2而不是其他任何东西的简单方法。