【问题标题】:Player is not changing between 'X' and 'O' in the program播放器没有在程序中的“X”和“O”之间切换
【发布时间】:2018-08-23 14:40:23
【问题描述】:

我想使用数组和循环在 C++ 中创建一个游戏(连接四个)。

  1. 首先我创建了一个 8x5 板。

  2. 其次,我提示用户选择从 1 到 6 的列。

  3. 当用户选择任一列时,该列的最后一行将从'.' 更改为'X''O'

一切正常,但播放器没有在void TogglePlayer(&player) 中的'X''O' 之间切换

#include <iostream>
#include <iomanip>
using namespace std;

const int rows = 8;
const int columns = 5;
char player = 'X';
//This function creates a 8x5 board
char matrix[rows][columns] = { '.','.','.','.','.',
                               '.','.','.','.','.',
                               '.','.','.','.','.',
                               '.','.','.','.','.',
                               '.','.','.','.','.',
                               '.','.','.','.','.',
                               '.','.','.','.','.',
                               '.','.','.','.','.' };

 //This function displays the board
void display()
{

    int width = 3;

    cout <<  setw(width) << "1" << setw(width) << "2" << setw(width) << "3" << 
    setw(width) << "4" << setw(width) << "5" << setw(width) << '\n';

    for (int i = 0; i < rows; i++)
    {
        for (int j = 0; j < columns; j++)
        {
            cout << setw(3) << matrix[i][j] << setw(3);
        }
        cout << endl;
    }
    cout << setw(width) << "1" << setw(width) << "2" << setw(width) << "3" << setw(width) << "4" << setw(width) << "5" << setw(width) << '\n';
 }


  //This the main function that executes the player's selected column
void input(char player)
{
    int a;
    cout << "Enter the column" << endl;
    cin >> a;
    if (a > 0 && a < 6)
    {
        for (int i = 7; i >= 0; i++)
        {
            if (matrix[i][a - 1] == '.')
            {
                matrix[i][a - 1] = player;
                break;
            }
        }
    }
}



//This function changes the players between 'X' or 'O'
void togglePlayer(char &player)
{
    if (player == 'O')
    {
        player = 'X';
    }
    else player = 'O';
}




int main()
{   
    while (true)
    {
        display();
        input(player);
        togglePlayer(player);
    }
    system("pause");
    return 0;
}

【问题讨论】:

  • 继续盯着下面一行:for (int i = 7; i &gt;= 0; i++),一直盯着它,直到你看到你的错误。看到后,在 Google 上搜索“未定义的行为”。
  • @SamVarshavchik 当我在 for (int i = 7; i &gt;= 0; i++) 上设置断点并执行时,我的程序运行良好,但它没有进入函数 TogglePlayer 为什么?
  • 你的 togglePlayer 函数对我来说看起来不错,顺便说一句。考虑将您的 char player 声明移动到 main 中(只需复制/粘贴该行),这样您就有一个效率较低的全局变量,这样就不会混淆全局 char player 与 togglePlayer 的局部范围 char &amp;player
  • ++ 一个变量从 7 到 0 需要很长时间。特别是如果您一次调试一行代码。

标签: c++


【解决方案1】:

正如问题的 cmets 部分所指出的,问题在于 for 循环:

for (int i = 7; i >= 0; i++)

当您在控制表达式中比较 i0 的值时,i 的值应该随着每次迭代而减小。

这里有一些东西可以帮助您避免将来出现循环中的错误。 阅读此question 及其答案,尤其是此one

【讨论】:

  • cmets 中已经给出了答案,并且 OP 找到了答案。我不想在这里再重复一遍。我写了这些信息作为答案,因为大多数人没有阅读所有的 cmets。但如果你坚持我也可以添加答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-03-13
  • 2015-02-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多