我的项目与举办网球比赛有关。首先,它要求用户输入玩家人数,并根据该人数进行锦标赛的一些阶段。
例如8人,则分3个阶段。 在第一阶段,玩家将两两对战,用户将选择每场比赛的获胜者。然后,获胜者需要进入第二阶段,获胜者之间将进行比赛,直到比赛中出现获胜者。
为此,我制作了一个结构和一个数组来存储获胜者的玩家编号,我想将这些保存的值用于代码的下一阶段,尽管代码在第一阶段保存了获胜者的编号,在进入下一阶段(例如:第二阶段)时,打印的数字是错误的,而不是获胜者。我曾尝试修复代码,这是我的尝试,但我无法理解问题所在。请帮我修复代码。
#include <stdlib.h>
#include <math.h>
typedef struct {
int player_num;
int beaten[10];
int num_beaten;
} Player;
typedef struct {
int num_players;
Player *players;
int winners[10];
int num_winners;
} Stage;
int getStageNum(int num_players) {
if (num_players == 1) {
return 0;
}
return log2(num_players) + 1;
}
Stage* createStage(int num_players) {
Stage *stage = (Stage*)malloc(sizeof(Stage));
stage->num_players = num_players;
stage->players = (Player*)malloc(sizeof(Player) * num_players);
for(int i=0; i<num_players; i++) {
stage->players[i].player_num = i+1;
stage->players[i].num_beaten = 0;
}
return stage;
}
void updateStage(Stage *stage, int match_num, int winner_num) {
stage->winners[stage->num_winners++] = winner_num;
}
int main() {
int num_players;
printf("Enter number of players: ");
scanf("%d", &num_players);
// Calculate number of stages
int num_stages = log2(num_players);
printf("Number of stages: %d\n", num_stages);
// Create the initial stage
Stage *stage = createStage(num_players);
// Play all the stages
for(int i = 1; i <= num_stages; i++) {
printf("\n\nStage %d:\n", i);
// Play matches in the current stage
int stage_index = pow(2, i-1) - 1;
int num_matches = pow(2, num_stages-i);
for(int j = 0; j < num_matches; j++) {
printf("\nMatch %d: Player %d vs Player %d\n", j+1, stage->players[stage_index+j*2].player_num, stage->players[stage_index+j*2+1].player_num);
// Get the winner of the match
int winner_num;
printf("Enter the player number who won this match: ");
scanf("%d", &winner_num);
updateStage(stage, stage_index+j+1, winner_num);
}
// Move the winners to the next stage
int num_winners = num_matches;
for(int j = 0; j < num_matches; j += 2) {
int winner1_num = stage->winners[stage_index+j];
int winner2_num = stage->winners[stage_index+j+1];
/*
printf("\nMatch %d: Player %d vs Player %d\n", j/2+1, winner1_num, winner2_num);
// Get the winner of the match
int winner_num;
printf("Enter the player number who won this match: ");
scanf("%d", &winner_num);
updateStage(stage, stage_index+num_winners+(j/2)+1, winner_num);
*/
}
}
您的代码有很多问题。您可能想检查第 52 行的 for 循环是否 -
for(int i = 1; i <= num_stages; i++) {
在增加阶段时正确实施,但在下一阶段继续从“玩家”数组中获取玩家。您可能希望避免在您的结构中使用“int winners[10]”,而是实现一个 array of 'stages',它有自己的 array of 'players'。通过这种方式,您可以正确使用 for 循环,并且可以将 current 'stage' 的获胜者移动到 next 'stages' player array。最后,不要忘记在使用完阶段后释放内存。