gpt4 book ai didi

c++ - 我可以在 IF 语句中将比较链接在一起吗?

转载 作者:太空宇宙 更新时间:2023-11-04 15:22:53 24 4
gpt4 key购买 nike

我目前正在为大学制作一个 naughts and crosses 程序。我已经完成了这项任务的基本任务,但是我在创建获胜条件以结束游戏时遇到了一些麻烦。以下是我到目前为止使用的所有代码:

#include <iostream>
#include <string>

using namespace std;

class Player
{
private:
char NorX;

public:

char Choose(char InitialValue)
{
NorX = InitialValue;
return InitialValue;
}

char GetNorX()
{
return NorX;
}
};

int main()
{
Player Player1;
Player Player2;

Player1.Choose('O');
Player2.Choose('X');

cout << "The board is being drawn please wait..." << endl;

const int Rows = 4;
const int Columns = 4;
char Board[Rows][Columns] = { {' ', ' ', ' ', ' ' },
{' ', '_', '_', '_' },
{' ', '_', '_', '_' },
{' ', '_', '_', '_' } };

for (int i = 0; i < Rows; ++i)
{
for (int j = 0; j < Columns; ++j)
cout << Board [i][j];
cout << endl;
}

cout << endl << endl;

int row;
int column;

do
{
do
{
cout << "Please enter the value of the row you would like to take ";
cin >> row;
}while (row != 0 && row != 1 && row != 2 && row != 3);


do
{
cout << "Please enter the value of the column you would like to take ";
cin >> column;
}while (column != 0 && column != 1 && column != 2 && column != 3);


Board [row][column] = Player1.GetNorX();

for (int i = 0; i < Rows; ++i)
{
for (int j = 0; j < Columns; ++j)
cout << Board [i][j];
cout << endl;
}

/*int row;*/
do
{
cout << "Please enter the value of the row you would like to take ";
cin >> row;
}while (row != 0 && row != 1 && row != 2 && row != 3);

/*int column;*/
do
{
cout << "Please enter the value of the column you would like to take ";
cin >> column;
}while (column != 0 && column != 1 && column != 2 && column != 3);

Board [row][column] = Player2.GetNorX();

for (int i = 0; i < Rows; ++i)
{
for (int j = 0; j < Columns; ++j)
cout << Board [i][j];
cout << endl;
}

if (Board[1][1] == Board[1][2] == Board[1][3] == 'O')
{
cout << endl << "Well done you win";
}

}while (column != 4 && row != 4);

system("pause");
}

问题出在if语句上,似乎对程序的运行没有任何影响。

最佳答案

在 C++ 中链接比较运算符的结果不是人们所期望的。正确的做法是用“逻辑与”连接它们 &&

if (Board[1][1] == 'O' && Board[1][2] == 'O' && Board[1][3] == 'O')

对于给定的例子

if (Board[1][1] == Board[1][2] == Board[1][3] == 'O')

你必须考虑operator precedence ,对于相等运算符 ==,它是从左到右。这意味着,该示例与(注意附加括号)相同

if ((Board[1][1] == Board[1][2]) == Board[1][3]) == 'O')

工作方式如下:

Board[1][1] == Board[1][2]

给出 truefalse。这将与下一部分进行比较

true == Board[1][3]

给出 false,因为 truefalse 永远不等于字符。这将与字符零进行比较

false == '0'

这将再次导致 false

关于c++ - 我可以在 IF 语句中将比较链接在一起吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14982813/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com