這個問題在這里已經有了答案: srand()——為什么只呼叫一次? (7 個回答) 昨天關閉。
我打算通過使用 C 語言中的陣列在 CMD 上制作一個蛇游戲,我已經對棋盤創建和游戲的部分進行了編碼,還沒有完全完成,但我還必須在桌子上創建蛇和食物.
我試圖除錯程式,我發現 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
uj5u.com熱心網友回復:
多次呼叫 srand() 可能會導致問題,具體取決于您要實作的目標。更多細節在這里。在使用rand()時,我個人是這樣學習的:
rand() % (25 1 - 0) 0;
rand() % (64 1 - 0) 0;
在主函式上方的函式宣告中,寫出變數名稱,不要只輸入 int。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/400313.html
