簡體   English   中英

將用戶輸入的值從一個函數傳遞到另一個C時出現問題

[英]Having issues passing user inputted values from one function to another C

我正在做一個井字游戲,當用戶輸入他們的舉動時,我需要確保隨機生成的數字與用戶不同,以及他們是否要重新生成另一個舉動。 當我有一個讓玩家移動的功能,然后是另一個產生隨機移動的功能時,問題就來了。 我似乎無法從get_player1_move到generate_player2_move中獲取row和col的值。

這是我聲明行和col變量的主要功能。

int main (){
char board[SIZE][SIZE];
int row, col;


clear_table(board);  //Clears the table
display_table(board);  //Display the table
do {
    get_player1_move(board, row, col); 
    printf("%d, %d", row, col);     //Have player 1 enter their move
    generate_player2_move(board, row, col); //Generate player 2 move
} while(check_end_of_game(board) == false); //Do this while the game hasn't ended

print_winner(board); //after game is over, print who won

 return 0;
}

這是get_player1_move函數,在該函數中我將獲得輸入行和列的值。

void get_player1_move(char board[SIZE][SIZE], int row, int col) {     //More work; test if game is over

printf("Player 1 enter your selection [row, col]: ");
scanf("%d, %d", &row, &col);

board[row-1][col-1] = 'O';
display_table(board);
}

現在,我想將分配給這兩個變量的值傳遞給此函數,以便可以對照隨機生成​​的移動進行檢查,但是當我打印出這些值時,它始終打印0、0。因此由於某種原因,我無法獲得值傳遞給此函數。 這是generate_player2_move函數。

void generate_player2_move(char board[SIZE][SIZE], int row, int col) {   //More work; test if game is over, also the check doesn't work

int randrow = 0, randcol= 0;

srand(time(NULL));

randrow= rand() % 3 + 1;

randcol= rand() % 3 + 1;

printf("%d, %d\n", row, col);

if ((randrow != row) && (randcol != col)) {

printf("Player 2 has enterd [row, col]: %d, %d \n", randrow, randcol);

board[randrow - 1][randcol - 1] = 'X';

display_table(board);
}
}

當我運行該函數時,printf(“%d,%d \\ n”,row,col); 當我希望它打印用戶在上一個函數中輸入的值時,繼續打印0,0。

您的程序中有多個問題。

首先讓我們了解一下您的printf()調用輸出0, 0的原因。 參數rowcol都是按值傳遞的局部變量。 這意味着,例如,如果通過scanf()調用在get_player1_move()函數中更改了row變量get,則不會在get_player1_move()函數之外進行更改。 因此main()函數中的變量row保持不變。

您可以使用按引用傳遞(指針)來解決此問題。 但是問題在於,播放器2的功能僅檢查播放器1選擇的最后一行和最后一列。但是您必須檢查所有行和列。 否則,字段可能會被覆蓋。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM