如何修改mostTotalMedals函数以统计总奖牌数而非金牌数?
重写mostTotalMedals函数以比较总奖牌数
当前的mostTotalMedals函数通过直接比较gold字段筛选金牌最多的国家,要改成比较单个国家的总奖牌数(金牌+银牌+铜牌),可以按以下方式修改:
方式一:直接在循环内计算单国总奖牌数
这种方式无需额外新增函数,逻辑直接明了:
// Function to find the country with the most total medals int mostTotalMedals(Country countries[]) { int index = 0; // Loop to find the country with the most total medals for (int i = 0; i < numCountries; i++) { // 计算当前遍历国家的总奖牌数 int currentTotal = countries[i].gold + countries[i].silver + countries[i].bronze; // 计算当前候选国家的总奖牌数 int candidateTotal = countries[index].gold + countries[index].silver + countries[index].bronze; if (currentTotal > candidateTotal) { index = i; } } return index; // 原代码缺失return语句,必须补充以返回结果 }
方式二:新增辅助函数优化可读性
如果希望逻辑更清晰,可以先写一个计算单个国家总奖牌数的辅助函数,再在mostTotalMedals中调用:
// 辅助函数:计算单个国家的总奖牌数 int getCountryTotalMedals(Country country) { return country.gold + country.silver + country.bronze; } // Function to find the country with the most total medals int mostTotalMedals(Country countries[]) { int index = 0; // Loop to find the country with the most total medals for (int i = 0; i < numCountries; i++) { if (getCountryTotalMedals(countries[i]) > getCountryTotalMedals(countries[index])) { index = i; } } return index; // 补充原代码缺失的return语句 }
注意事项
- 原代码的
totalMedals函数是计算所有国家的奖牌总数,不是单个国家的,因此无法直接复用在本次需求中。 - 原
mostTotalMedals函数末尾缺少return index;语句,这会导致程序出现未定义行为,必须补上。 - 如果需要处理总奖牌数并列的情况(比如多个国家总奖牌数相同),可以根据需求调整逻辑,比如保留第一个出现的国家,或者修改函数返回值类型以返回所有并列国家的索引列表。
内容的提问来源于stack exchange,提问作者Jtron17
相关产品推荐
相关产品推荐

