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

标签 c++ artificial-intelligence

我用 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/

相关文章:

c++ - 为什么 C++ 使用指针?

artificial-intelligence - 支持向量机和神经网络

c++ - 有人可以解释一下 openCV 中的 detectMultiScale

machine-learning - 类型对象 'GridSearchCV' 没有属性 'cv_results_' ?

c++ - ./libmylib.so : undefined reference to `submarinex::LIB::kCount'

c++ - 分配器作为 vector 和列表中的默认参数

c++ - 在 C++ 方法中更改结构变量

构建正确英语句子的 C# 库

c++ - 新 std::map 条目中指针的默认值

c++ - C++ 中的依赖注入(inject)