gpt4 book ai didi

c - 给定数组中的最小奇数

转载 作者:太空狗 更新时间:2023-10-29 15:28:13 24 4
gpt4 key购买 nike

此代码应该在给定数组中找到最小的奇数并将其存储在 min 中,但是当我尝试打印 min 时,它总是打印 0.

int smallestodd(int x[5]){
int j;
int k[5];
int p = 0;
int r = 0;

for(int h =0; h<5;h++){

j = x[h] % 2;
if(j == 1){
int temp =x[h];
k[p] =temp;
p++;
}
}

int min = k[0];


while(k[r] !=0){
if(k[r] < min ){
min = k[r];
r++;
}
}

return min;
}

最佳答案

假设数组中有一个奇数 -- 假设尝试在只有偶数(或没有数字)的数组中找到最小奇数是 UB :)

index = 0;
while (arr[index] % 2 == 0) index++; // skip even numbers
min = arr[index++]; // first odd number
while (index < length) {
if (arr[index] % 2) {
if (arr[index] < min) min = arr[index];
}
index++;
}

关于c - 给定数组中的最小奇数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54180226/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com