You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C语言查找最高得分玩家函数的逻辑错误排查求助

问题分析与修正

你的代码存在几处逻辑错误,导致并列高分处理异常,下面逐个拆解并给出修复方案:

核心错误点

  • 最高分初始化不合理:high_num初始设为0,若玩家分数全为负数,会错误判定最高分是0,应初始化为数组第一个玩家的分数。
  • 找到更高分时未重置记录:发现更高分后,仅将新位置加入position数组,但未清空之前存储的低分位置,导致后续打印时旧位置被误判为高分玩家(比如你测试用例中10分玩家的位置未被清除,最终被当成16分玩家输出)。
  • 并列高分未记录位置:遇到与最高分相等的分数时,仅修改players计数,未将当前玩家位置存入position数组,导致并列玩家信息丢失。
  • 无效的自增语句:players = players++;是错误写法,后置自增players++会先返回当前值再自增,这条语句等价于players = players,直接写players++即可。

修正后的代码

/* Function display_highest_score() searches the player score array for the highest value and
   any repetitions before printing the results to the screen.
   Parameters: The player array, score array, and number of players.
   Returns: Nothing.*/
void display_highest_score(char player_array[][STRING_LENGTH], int score_array[], int num_players) {
    // 处理空数组的边界情况
    if (num_players <= 0) {
        printf("\nNo players to evaluate.\n");
        return;
    }

    int high_num = score_array[0]; /* 初始化为第一个玩家的分数 */
    int position[MAX_PLAYERS] = { 0 }; /* 存储最高分玩家的位置 */
    int players = 1; /* 最高分玩家的数量 */
    int j = 1; /* position数组的索引指针 */
    position[0] = 0; /* 先存入第一个玩家的位置 */

    /* 遍历数组寻找最高分及并列玩家 */
    for (int i = 1; i < num_players; i++) {
        if (high_num < score_array[i]) {
            // 找到更高分,重置所有记录
            high_num = score_array[i];
            position[0] = i;
            j = 1;
            players = 1;
        }
        else if (high_num == score_array[i]) {
            // 遇到并列高分,记录位置并增加计数
            position[j] = i;
            j++;
            players++;
        }
    }

    /* 打印结果 */
    printf("\nPlayers with the highest score of %d are:\n\n", high_num);
    for (j = 0; j < players; j++) {
        printf("--> %s\n", player_array[position[j]]);
    }
}

修正说明

  • 新增num_players <=0的边界处理,避免空数组引发错误。
  • 初始化时直接将第一个玩家的分数和位置存入对应变量,从第二个玩家开始遍历,减少冗余操作。
  • 找到更高分时,直接重置position数组的第一个元素为当前玩家位置,同时将计数变量j和players重置为1,彻底清空之前的低分记录。
  • 遇到并列高分时,将当前玩家位置存入position数组的下一个索引,同步更新计数。
  • 修复了无效的自增语句,直接使用players++完成计数更新。

用你提供的测试数组score_array[10] = {3,1,0,10,4,8,10,0,3,16}测试,该函数会正确输出最高分16对应的玩家,不会再错误打印10分的玩家。

内容的提问来源于stack exchange,提问作者Nath

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 22:52:53