我正在尝试创建一个 C 函数,它接受一个数组,找到最小的元素,并将该元素的值设置为零。
到目前为止,这是我的功能。
void find_minimum(double a[], int n) {
int i, smallest = 0;
smallest = a[0];
for (i = 0; i < n; i++) {
if (a[i] < smallest) {
smallest = a[i];
}
a[i] = 0;
}
}
当我运行它时,除了最后一个索引之外的每个索引都是零,但我只希望最小的元素为零。
最佳答案
你的代码有一些问题,我很惊讶你的编译器没有对你造成影响。
void find_minimum(double a[], size_t n) {
size_t i, index;
double smallest;
// sanity check to make sure we're not accessing outside allocated memory
if (n > 0) {
smallest = a[0];
index = 0;
} else {
// nothing left to do here
return;
}
// start at 1 because 0 is initial default
for (i = 1; i < n; i++) {
if (a[i] < smallest) {
smallest = a[i];
index = i;
}
}
// assign only the smallest index
a[index] = 0.0;
}
如有任何问题,请随时发表评论。
关于c - 找到数组的最小元素并将其索引设置为 0,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37822400/