2013-05-10 34 views
1

我在C++(控制台)中编写了一个简单的Langtons Ant。但是(不知道为什么)我每次运行我的程序时都会抛出核心: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; 
} 

我该如何摆脱这个错误?

+1

删除代码,直到它停止崩溃。 – 2013-05-10 14:28:23

+0

尝试使用valgrind或gdb运行它 – nogard 2013-05-10 14:38:12

回答

4

它可能使用模像这样:

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

记住negative % positive = negative,这意味着你可以得到出界。

+0

谢谢!将其更改为:'y =((y-1));如果(y <0)y *(-1); y = y%n;'但仍然是核心倾弃。 – yak 2013-05-10 14:34:47

+0

@yak它应该是'y%= n;如果(y <0)y + = n;'尽管我认为这不会导致核心转储。 – Pubby 2013-05-10 14:38:28