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

编写冒泡排序函数遇异常:执行后仍输出未排序列表求排查

问题排查与修复方案

你的代码存在两个关键问题,导致排序逻辑未正确执行:

1. 内层循环变量增量错误

在sort_cities函数的内层for循环中,循环变量更新语句错误地写为i++,而非j++:

// 错误代码
for (int j = 0; j < NUM_CITIES - i - 1; i++)

这个错误会导致外层循环的i被快速递增到NUM_CITIES-1,外层循环仅执行一次就终止,排序逻辑完全没机会运行。修正为:

// 正确代码
for (int j = 0; j < NUM_CITIES - i - 1; j++)

2. 数组初始化语法错误

在temps数组的初始化项中,"Boston"对应的温度值多写了一个闭合双引号:

// 错误代码
{"Boston", 82"}

这会触发编译语法错误,修正为:

// 正确代码
{"Boston", 82}

关于主函数获取结果的疑问

你的怀疑不成立:temps是全局数组,sort_cities函数直接修改的是全局内存中的数组内容,主函数无需额外传递参数就能访问到修改后的结果。

修复后的完整代码

#include <cs50.h>
#include <stdio.h>

#define NUM_CITIES 10

typedef struct
{
    string city;
    int temp;
}
avg_temp;

avg_temp temps[NUM_CITIES] = {
    {"Austin", 97}, {"Boston", 82}, {"Chicago", 85},
    {"Denver", 90}, {"Las Vegas", 105}, 
    {"Los Angeles", 82}, {"Miami", 97},
    {"New York", 85}, {"Phoenix", 107},
    {"San Fransisco", 66}
};

void sort_cities(void);

int main(void)
{
    sort_cities();

    printf("\nAverage July Temperatures by City\n\n");

    for (int i = 0; i < NUM_CITIES; i++)
    {
        printf("%s: %i\n", temps[i].city, temps[i].temp);
    }
}

void sort_cities(void)
{
    for (int i = 0; i < NUM_CITIES - 1; i++)
    {
        for (int j = 0; j < NUM_CITIES - i - 1; j++)
        {
            if (temps[j].temp < temps[j + 1].temp)
            {
                avg_temp initial = temps[j];
                temps[j] = temps[j + 1];
                temps[j + 1] = initial;
            }
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 14:15:08