c++入门课程作业:井字游戏;设置数组时出现错误

Introductory C++ course assignment: Tic-Tac-Toe; Errors when setting up array

本文关键字:设置 游戏 数组 错误 程作业 作业 c++      更新时间:2023-10-16

我们的项目是制作一款井字游戏。这应该是非常基本的,因为它是编程课程的基础(底线入门级)。我这样说是因为我可能得到的任何帮助都不能超出我的知识范围,否则会显得可疑。

我需要显示在板上的数字(X和O的每个空间将有一个地方持有1 - 9的数字)从我设置的数组中拉出来。问题是,我不能让它按照我想要的方式来做。

因此,在下面注释的帮助下,我已经整理了一下我的代码(这就是编辑的原因,也可能是问题和答案不匹配的原因)。

当前的问题是,我不知道如何允许用户将数字更改为"X"或"O"。

using namespace std;
int board[9] {
    1, 2, 3, 4, 5, 6, 7, 8, 9
};
void displayBoard(void) {
char index;
    for (int i=0; i < 9; i++)
    cout << endl;
    cout << board[index] << "|" << board[index+1] << "|";  cout << board[index+2] << endl;
    cout << "-----" << endl;
    cout << board[index+3] << "|" << board[index+4] << "|" << board[index+5] << endl;
    cout << "-----" << endl;
    cout << board[index+6] << "|" << board[index+7] << "|" << board[index+8] << endl;
    index = index + 9;
}
void playerInput(void) {

    for (int i=0; i < 9; i++) {
        cin >> board[index]
    }
}
int main (int argc, char *argv[]) {
    displayBoard();

}

您有4个错误将导致程序失败。1)首先将board声明为char类型,然后再声明为char类型[]2)你循环i,它并不存在。而是循环遍历index。3) playerInput和move还没有定义。4)你在读取角色后立即将移动值分配给玩家输入。所以你从输入流中为playerInput分配一个值,但立即覆盖它。

除了这些技术细节,这里有一些文体技巧:Cout和cin级联。这意味着你可以并且应该替换:

cout << board[index]; cout << "|"; cout << board[index+1] << "|"; 
与这个:

cout << board[index] << "|" << board[index+1] << "|"; 

此外,您应该定义函数来处理您的值,而不是将它们保留在全局作用域中。但是现在,我建议集中理解赋值和变量声明。