我试图让我的程序扫描棋盘寻找 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/