此代码应该在给定数组中找到最小的奇数并将其存储在 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/