C为什么这个for循环在满足条件时不执行?

标签 c for-loop

我有一个 for 循环,用于找到距离特定危险船只最近的直升机。

我遇到的问题是我需要从我的搜索中忽略 LifeBoats(它们具有 L 的类型,它是结构中的单个字符)并且只关注直升机,由 H 是结构中的单个字符。

我遇到的问题是,当我有这个 for 循环时:

closest_index = 0;

for (j = 0; j < asset_size; j++) {
        printf("type : %c \n", (assets + j)->type);
        if ((assets + j)->type == 'H') {
            if (((assets + j) ->distance_from_mayday) < ((assets + closest_index) ->distance_from_mayday)) {
                closest_index = j;
                printf("closest_index heli = %d \n", closest_index);

            }
        }
    }

它肯定会被调用,我添加了这行:

 printf("type : %c \n", (assets + j)->type);

就在比较之前,它在控制台中产生了这个结果:

type : L 
type : L 
type : L 
type : L 
type : L 
type : L 
type : L 
type : L 
type : L 
type : L 
type : L 
type : L 
type : L 
type : L 
type : L 
type : L 
type : L 
type : L 
type : L 
type : L 
type : L 
type : L 
type : L 
type : L 
type : L 
type : L 
type : L 
type : L 
type : L 
type : L 
type : L 
type : H 
type : H 
type : H 
type : H 
type : H 
type : H

如您所见,存在 H 的值,所以我不明白为什么这个 for 循环没有按预期执行,有什么想法吗?

最佳答案

我猜,列表中的第一个元素是“L”类型,并且小于或等于任何“H”值。您的 closest_index 标记不会因此移动。

closest_index最好记录距离本身或使用不可能的起始值(-1?)

编辑:

建议代码:

struct asset *result = NULL;

for (j = 0; j < asset_size; j++) {
     if (assets[j].type != 'H')
         continue;
     if (!result || assets[j].distance < result->distance)
         result = &assets[j];
}

关于C为什么这个for循环在满足条件时不执行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20230388/

相关文章:

javascript - 在 JavaScript 中使用 for 循环组合两个数组

C "for"循环更改函数内的指针值

php foreach里面for语句问题

java - StringIndexOutOfBoundsException 不清楚

c - 错误: Expected unqualified-id before numeric constant

c - 段错误,尽管代码从未执行?

c - 带微 Controller PIC 的 Invensense IMU3000

javascript - 使用 Javascript 验证第二个数组中的值是否对应于第一个数组的平方值的函数

c - 循环索引比较未按预期组装

c - 从文件数据打印星号