c - 找到数组的最小元素并将其索引设置为 0

标签 c arrays

我正在尝试创建一个 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/

相关文章:

javascript - 在前 N 个自然数的数组中找到 1、2、3 个缺失的数字

c - qt connect() 的文档页面

javascript - Java 将 byte[] 转换为 BigInteger

c - 如何设置指向二维数组的指针

c - 通过 C 中的函数操作动态数组

Python在列表中搜索多个单词

c - 如何在 C 中将 uint_64 的十六进制表示形式复制到十六进制的无符号字符数组?

c - 尝试在 C 中释放结构时出现问题

c - 区分数据类型和数据结构

c - 大型与嵌套状态机