为什么我第二次调用自己的函数时 rand() 函数不起作用?

Why doesn't rand() function work the second time i call my own function?

我打算在 CMD 上使用 C 语言的数组制作一个贪吃蛇游戏,我已经编写了棋盘创建和游戏的部分代码,但还没有完全完成,但我还必须创建贪吃蛇和table.

中的食物

我试图调试程序,我发现 rand() 函数在我第二次使用我的函数时不起作用,而且当我尝试多次调用这些函数时它也崩溃了。我无法解决为什么。

int main()
{

int row,column;
create_snake(row,column,2);
create_snake(row,column,3);
}
void create_snake(int row,int column,int x){

srand(time(NULL));

row=rand()%25;
column=rand()%64;
}

这里是完整的代码(还没有完全完成但是它崩溃了)

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int board[25][64];

void create_snake(int,int,int);


int main()
{

int row,column;

for(int i=0;i<25;i++){   //creating board
        for(int a=0;a<64;a++){
              if(i == 0 || i == 24){
            board[i][a]=1;
            }else if(a == 0 || a==63){
            board[i][a]=1;
            }else{
                board[i][a]=0;
            }
        }
    }

create_snake(row,column,2); //creating snake



/*for(int i=0;i<25;i++){
        for(int a=0;a<64;a++){
        printf("%d",board[i][a]);
}
printf("\n");
}
*/
create_snake(row,column,3); //creating food

}



void create_snake(int row,int column,int x){

srand(time(NULL));

row=rand()%25;
column=rand()%64;

printf("%d   %d",row,column);
printf("\n");
/*if(board[row][column]==1){
  // create_snake(row,column,x);

}else if(board[row][column]==0){
    board[row][column]=x;

}else{
    //create_snake(row,column,x);
}
*/
}
v

多次调用 srand() 可能会导致问题,具体取决于您想要实现的目标。更多详细信息 here。在使用rand()的时候,我个人是这样学的:

rand() % (25 + 1 - 0) + 0;
rand() % (64 + 1 - 0) + 0;

在主函数上方的函数声明中,写出变量名,不要只键入 int。