C语言查找数组前三大数值并关联对应名称的实现问题
C语言双数组匹配奖牌排名问题修复
存在的两个核心错误
- 语法错误:
else if (totalMedals[i] > third)分支缺失花括号,后续的strcpy(thirdName, countryNames[i]);逻辑不属于该条件判断,会在每次循环时无条件执行,最终第三名国家名称永远是遍历的最后一个国家,和奖牌数完全不匹配。 - 逻辑错误:当有新的更高奖牌数出现导致排名更新时,仅更新了新位次的国家名称,没有同步将旧位次的名称向下传递。比如原本的第一名变成第二名时,没有把旧第一名的国名赋值给secondName,会出现国名和奖牌数错位的问题。
修复后完整代码
#include <stdio.h> #include <string.h> #include <limits.h> #define COUNTRIES 10 void rankTopThreeByTotal (int totalMedals[COUNTRIES], char countryNames [COUNTRIES][100]) { int i, first, second, third; char firstName[100], secondName[100], thirdName[100]; // 数组长度与入参匹配,避免字符串溢出 third = first = second = INT_MIN; for (i = 0; i < COUNTRIES; i++) { if (totalMedals[i] > first) { // 排名整体下移,国名同步移位 third = second; strcpy(thirdName, secondName); second = first; strcpy(secondName, firstName); first = totalMedals[i]; strcpy(firstName, countryNames[i]); } else if (totalMedals[i] > second) { third = second; strcpy(thirdName, secondName); second = totalMedals[i]; strcpy(secondName, countryNames[i]); } else if (totalMedals[i] > third) { third = totalMedals[i]; strcpy(thirdName, countryNames[i]); } // 补充花括号包裹分支逻辑 } printf("%s: %d\n", firstName ,first); printf("%s: %d\n", secondName ,second); printf("%s: %d\n", thirdName ,third); } int main(void) { int totalMedals[COUNTRIES] = {13, 14, 18, 12, 7, 6, 2, 9, 5, 4}; char countryNames [COUNTRIES][100] = {"Japan", "USA", "China", "ROC", "UK", "Australia", "Kosova","Italy","France", "Canada"}; rankTopThreeByTotal(totalMedals, countryNames); return 0; }
运行输出
China: 18 USA: 14 Japan: 13
内容的提问来源于stack exchange,提问作者Jacob G
相关产品推荐
相关产品推荐

