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

C++代码调试:如何从vector中获取非零最小与次小值

问题分析与解决方案

核心错误拆解

你的代码存在三个关键逻辑错误,直接导致结果偏离预期:

  • 初始值设置错误:closCityDist和closeCity初始设为0,但我们要找的是大于0的最小值和次小值,初始值应设为远大于所有可能距离的数值(比如INT_MAX,需包含<climits>头文件),否则0会直接干扰最小值判断。
  • 第一个循环条件逻辑颠倒:原条件closCityDist < distances[...] && distances[...] <1会把城市到自身的0距离选为最小值,且逻辑是找比当前closCityDist大且小于1的数,完全违背「找大于0的最小值」的需求。
  • 第二个循环连续比较语法错误:C++不支持a < b < c的连续比较写法,编译器会解析为(a < b) < c,布尔值转成0或1后,你的条件实际变成0 < distances[...](因初始closeCity为0,closCityDist < closeCity是false即0),再加上distances[...] >1,只会选中最大的2395,完全不是次小值逻辑。

修正后的代码

#include <climits> // 引入头文件使用INT_MAX

// 初始化变量为极大值,确保所有有效距离都能覆盖
int closCityDist = INT_MAX;
int farCity = INT_MAX; // 按你的需求将变量名改为farCity,更符合语义

// 第一步:找大于0的最小值
for (int i = 0; i < TRAVELCITIES; i++) {
    int currentDist = distances[(depCity * 15) + i];
    // 只筛选大于0的距离,且比当前最小值更小
    if (currentDist > 0 && currentDist < closCityDist) {
        closCityDist = currentDist;
    }
}

// 第二步:找次小值(比最小值大的最小距离)
for (int i = 0; i < TRAVELCITIES; i++) {
    int currentDist = distances[(depCity * 15) + i];
    // 距离需大于最小值,同时比当前次小值小
    if (currentDist > closCityDist && currentDist < farCity) {
        farCity = currentDist;
    }
}

cout << "The two closest cities to " << cities[depCity] << " are " << closCityDist << " and " << farCity << " miles away." << endl;

效率优化:单次遍历完成查找

可以合并两个循环,一次遍历同时找到最小值和次小值,提升效率:

#include <climits>

int closCityDist = INT_MAX;
int farCity = INT_MAX;

for (int i = 0; i < TRAVELCITIES; i++) {
    int currentDist = distances[(depCity * 15) + i];
    if (currentDist <= 0) {
        continue; // 跳过无效的0或负数距离
    }
    if (currentDist < closCityDist) {
        // 当前距离更小,将原最小值降级为次小值
        farCity = closCityDist;
        closCityDist = currentDist;
    } else if (currentDist < farCity && currentDist != closCityDist) {
        // 当前距离比次小值小,且不等于最小值(避免重复值干扰)
        farCity = currentDist;
    }
}

使用你提供的测试数据运行后,会得到正确结果:
The two closest cities to Denver are 942 and 1064 miles away.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 14:12:04