【问题标题】:Why doesn't rand() function work the second time i call my own function? [duplicate]为什么我第二次调用自己的函数时 rand() 函数不起作用? [复制]
【发布时间】:2021-12-31 10:06:00
【问题描述】:

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

我试图调试程序,我发现 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()。 time(NULL) 可能返回相同的数字。两个电话。所以你将 rand() 重置为相同的种子,导致相同的数字
  • srand(time(NULL));放在main()的前面,以后不要再调用它了。
  • 你能控制递归深度吗?崩溃时递归有多深?你需要递归吗?你可以在minimal reproducible example 中显示它吗?
  • 将代码放入问题中。 minimal reproducible example 意味着我可以复制代码并编译它(无需添加或修改它)并得到与您相同的错误。
  • 嗯,知道了,不过没关系,rand() 只留下一个 srand 后现在可以正常工作,而且递归现在也不会崩溃,所以解决了,谢谢大家

标签: c random


【解决方案1】:

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

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

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

【讨论】:

  • 为什么只写 int 会导致问题?我已经更改了它并且程序不再崩溃,但我想如果我不写变量的名称,该函数需要一个字面整数而不是变量?像 3?
  • pion, rand() % (25 + 1 - 0) + 0;int board[25][64]; 相差一个,这使得 26 个不同的 rowrow=rand()%25; 很好。
猜你喜欢
  • 2013-04-08
  • 2021-06-18
  • 2018-11-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多