gpt4 book ai didi

c++ - C++ 中的 Langtons Ant(控制台)- 核心转储

转载 作者:行者123 更新时间:2023-11-30 01:59:14 24 4
gpt4 key购买 nike

我用 C++(控制台)编写了一个简单的 Langtons Ant。但是(真的不知道为什么)我每次运行我的程序时都会得到一个核心转储:

#include <iostream>
#include <ctime>
#include <cstdlib>

using namespace std;

int main()
{
srand(time(NULL));

bool endGame = false;
enum compass {north, east, south, west};
compass dir = north;
int x = 0, y = 0;
int n = 30, m = 30;

int **board = new int*[n];
for(int i = 0; i <n; i++)
board[i] = new int[m];

for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
board[i][j] = rand()%2;

long count = 0;
while(!endGame)
{
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
//Print board
if(board[i][j] == 0)
cout << '+';
else
cout << '#';
}
cout << endl;
}

//Ant
if (board[x][y] == 0)
{
board[x][y] = 1;
switch (dir){
case north:
dir = east;
x = ((x+1)%m);
break;
case east:
dir = south;
y = ((y-1) % n);
break;
case south:
dir = west;
x = ((x-1) % m);
break;
case west:
dir = north;
y = ((y+1) %n);
break;
}
}else
{
board[x][y] = 0;
switch(dir){
case north:
dir = west;
x = ((x-1) % m);
break;
case west:
dir = south;
y = ((y-1) % n);
break;
case south:
dir = east;
x = ((x+1)%m);
break;
case east:
dir = north;
y = ((y+1) %n);
break;
}
}
cout << endl << count << endl;
count++;
cin.sync();
cin.get();
}
cin.sync();
cin.get();
return 0;
}

我怎样才能摆脱这个错误?

最佳答案

这可能是这样使用模数:

x = ((x-1) % m);

请记住 negative % positive = negative,这意味着您可以越界。

关于c++ - C++ 中的 Langtons Ant(控制台)- 核心转储,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16484567/

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