c++ - If 语句导致程序因递归而崩溃

标签 c++ if-statement recursion artificial-intelligence

我试图让我的程序扫描棋盘寻找 AI 的移动,如果我有第一个语句本身,if 语句就可以工作,但如果我添加 else if 语句并崩溃。

void BoardSet::foxNextToSheep(int x, int y, int& moves)
{

    if(board[x+1][y] == 'S' && board[x+2][y] == '.') 
    {
        x = x + 2;
        moves++;
        foxNextToSheep(x, y, moves);
    }
    else if(board[x-1][y] == 'S' && board[x-2][y] == '.')
    {
        x = x - 2;
        moves++;
        foxNextToSheep(x, y, moves);
    }
}

我假设这是由于递归,什么是更好的方法?

我意识到这是因为 board[x-1][y] 导致 x 变为负数并且不起作用。有办法阻止这种情况发生吗?

class BoardSet {
public:

//Functions used for foxes
    bool findFox(int x, int y);
    void foxNextToSheep(int x, int y, int& moves);

private: 
    char board[7][8];
    int sheep;
    int foxes;
};

class Foxes {
public:

void foxesProcess(BoardSet& board);
void findFoxes(BoardSet& board);
void checkForPossibleMoves(BoardSet& board);
void print();



private:
    int foxes[2][2];


};


void Foxes::checkForPossibleMoves(BoardSet& board)
{
    int moves1 = 0;
    int foxOneX = foxes[0][0];
    int foxOneY = foxes[0][1];
    board.foxNextToSheep(foxOneX, foxOneY, moves1);
    cout << moves1 << endl;

}

调用检查移动

void Foxes::foxesProcess(BoardSet& board)
{
    cout << "The foxes move: ";
    findFoxes(board);
    checkForPossibleMoves(board);

}

从主要

void processGame(istream& in)
{
    int repeat = 1;

    BoardSet board;
    Sheep sheep;
    Foxes foxes;
    initalizeBoard(in, board);
    while(repeat)
    {
        board.checkForWin(repeat);
        if(repeat == 0)
            break;
        sheep.sheepProcess(board);
        board.print();
        board.checkForWin(repeat);
        if(repeat == 0)
            break;
        foxes.foxesProcess(board);
    }
}

最佳答案

您没有在函数中进行任何边界检查,因此假设 board只是一个标准数组或一个不绑定(bind)检查的类,然后 when x<=1您将越界并进入未定义的行为。

在没有看到更多代码的情况下,最明显的检查和修复是这样的:

else if( x > 1 && (board[x-1][y] == 'S' && board[x-2][y] == '.') )

您在 if 上也有边界检查问题语句,如果x >= 4那么你也会越界:

if( x <= 4 && (board[x+1][y] == 'S' && board[x+2][y] == '.') ) 

如果您决定更改它,拥有某种定义最大值的变量会很有帮助。

关于c++ - If 语句导致程序因递归而崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15962236/

相关文章:

C++结构二维字符串成员初始化

c++ - Windows 中的 gdb : different behaviour when debugging compiled C and C++ code

javascript int 计算错误

recursion - 查找由列表组成的方阵的对角线

python - 使用Python递归进行日常编码挑战

c++ - 函数和方法的放置和使用

c++ - windows 8.1下Matlab 2014b安装SPAMS工具箱的方法

java - 将 If 语句更改为 Java 中的函数

java - 模糊的条件 Java 语法

linux - linux 文件搜索中的递归 - Bash 脚本