我有一个 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/