我有一些生活游戏的代码,它接受用户输入并显示输入哪些单元格作为活着输入,但无论如何都会打印一行四行*。我已经弄乱了很多不同的方式改变了一些东西,但它要么仍然打印相同的东西,要么根本不显示任何东西。我已经完成了多个论坛和网站的搜索,但我找到的每个代码都完全不同,这是我所期望的(包括来自stackoverflow的代码)。
#include <iostream>
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include <conio.h>
using namespace std;
#include <memory.h>
int main ()
{
const long MaxCols (10);
const long MaxRows (10);
const time_t WaitTime (3);
bool Board [MaxRows + 2] [MaxCols + 2];
long CurrCol;
long CurrRow;
time_t StopTime;
long Generation;
long OriginalArray[MaxRows][MaxCols];
long NewArray[MaxRows][MaxCols];
long Neighbors;
do
{
cout << "Enter a row and col for the living cell: ";
cin >> CurrRow >> CurrCol;
} while (CurrRow != 0 && CurrCol != 0);
for (Generation = 1; ; Generation++)
{
//Display the current generation on the board
system("cls");
cout << "\tCurrent Generation: " << Generation << endl;
for (CurrRow = 1; CurrRow <= MaxRows; CurrRow++)
{
for (CurrCol = 1; CurrCol <= MaxCols; CurrCol++)
cout << (Board [CurrRow + 2] [CurrCol + 2] ? ' ' : '*');
cout << endl;
}
//Loop to determine nieghbors
for(CurrRow=1; CurrRow <= MaxRows + 2; CurrRow++)
{
cout << endl;
for (CurrCol = 1; CurrCol <= MaxCols + 2; CurrCol++)
{
if (OriginalArray[CurrRow][CurrCol] == '*')
{
Neighbors = (OriginalArray, CurrRow, CurrCol);
if (Neighbors != 3 || Neighbors != 4 )
NewArray[CurrRow][CurrCol] = ' ';
else
NewArray[CurrRow][CurrCol] = '*';
}
else
{
Neighbors = (OriginalArray, CurrRow, CurrCol);
if (Neighbors != 2 || Neighbors != 3 )
NewArray[CurrRow][CurrCol] = ' ';
else
NewArray[CurrRow][CurrCol] = '*';
}
cout << "Touch any key to halt the program";
StopTime = time(0) + WaitTime; // time(0) gives the number of seconds since Jan 1, 1970
while (time (0) < StopTime) // keep looping until the current time catches the stop time
if (_kbhit()) //true if the user has hit a key, false if not hit a key
{
cout << "\nBye" << endl;
exit(0);
}
else;
}
}
}
}
答案 0 :(得分:1)
乱搞无法调试程序。当它没有按照您的预期行事时,您的第一步应该是尝试理解原因。通过制作什么,根据您的经验水平,基本上是对代码的随机更改,您只会让事情变得更糟。正如Oli所说,调试器是最好的工具。你应该学习如何使用你的。
查看代码可能存在很多错误,但有一个错误跳出来,这就是
Neighbors = (OriginalArray, CurrRow, CurrCol);
我不知道为什么你认为这会计算邻居的数量,但相信我不会。我想你猜了一下,然后当编译器没有抱怨你就认为猜测是对的。我不敢。
所以首先要集中注意力。您需要一些新代码来计算活动邻居的数量。想一想。
上面没有代码可以在Board中输入值。这里有一些代码可以做到。这是正确的,但这并不意味着它将适用于需要很多工作的其余代码。
// baord uses false for dead cells and true for living cells
bool Board [MaxRows + 2] [MaxCols + 2];
// initially make the whole board dead
for (int i = 0; i < MaxRows + 2; ++i)
for (int j = 0; j < MaxCols + 2; ++j)
Baord[i][j] = false;
// now ask the user for some live cells
for (;;)
{
cout << "Enter a row and col for the living cell (0 0 to quit): ";
int i, j;
cin >> i >> j;
if (i == 0 && j == 0)
break; // user entered 0 0 so quit loop
Board[i][j] = true; // set position i,j to live
}
您的代码中缺少的两个部分最初将整个Board设置为死亡,其次,一旦您从用户获得了一个活动单元的坐标,您就没有做任何设置该单元生存的内容。
让我对你的代码感到困惑的另一件事是你有不同规模的电路板
bool Board [MaxRows + 2] [MaxCols + 2];
long OriginalArray[MaxRows][MaxCols];
long NewArray[MaxRows][MaxCols];
为什么董事会有+ 2
而其他董事会没有。这对我来说毫无意义。