最近我发现了一些我很感兴趣的代码,但是我不能正确地理解它,所以有人能给我解释一下吗?
这是康威的生命游戏。我想这一行可以像一个问题,1表示真,0表示假;对吗?2但是为什么没有布尔值呢?
void iterGen(int WIDTH, int HEIGHT, char curMap[WIDTH][HEIGHT])
{
int i, j;
char tempMap[WIDTH][HEIGHT];
for (i = 0; i < WIDTH; i++)
{
for (j = 0; j < HEIGHT; j++)
{
int neighbors = 0;
neighbors += curMap[i+1][j+1] == '*' ? 1 : 0;
neighbors += curMap[i+1][j] == '*' ? 1 : 0;
neighbors += curMap[i+1][j-1] == '*' ? 1 : 0;
neighbors += curMap[i][j+1] == '*' ? 1 : 0;
neighbors += curMap[i][j-1] == '*' ? 1 : 0;
neighbors += curMap[i-1][j+1] == '*' ? 1 : 0;
neighbors += curMap[i-1][j] == '*' ? 1 : 0;
neighbors += curMap[i-1][j-1] == '*' ? 1 : 0;
if (curMap[i][j] == ' ')
{
tempMap[i][j] = neighbors == 3 ? '*' : ' ';
}
else if (curMap[i][j] == '*')
{
tempMap[i][j] = neighbors < 2 || neighbors > 3 ? ' ' : '*';
}
}
}
for (i = 0; i < WIDTH; i++)
{
for (j = 0; j < HEIGHT; j++)
{
curMap[i][j] = tempMap[i][j];
}
}
}
1条答案
按热度按时间a11xaf1n1#
First, a couple of comments.
is a redundant way of writing
since the comparison operators already return
1
or0
.But neither are as clear as
1 meaning true and 0 meaning false; is that correct? But why is there no bool?
Not quite.
0
is false (including0
as a pointer,NULL
). All other values are true.Now, on to the question.
But why there is no bool?
But there is:
_Bool
.stdbool.h
providesbool
as an alias, as well as the macrostrue
andfalse
.Demo on Compiler Explorer
Note that none of the variables in the snippet you posted are booleans, so I have no idea why that code was included in your question.