C++控制台中的兰顿蚂蚁 – 核心转储

我用C++编写了一个简单的兰顿蚂蚁控制台程序。但是(我不知道为什么)每次运行程序时都会出现核心转储错误:

#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);

请注意负数 % 正数 = 负数,这意味着你可能会超出边界。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注