c - 如何在C中打印数组中值的位置

标签 c arrays

我正在使用 for 循环来搜索数组中存在的最小值并打印该值。我想打印出该值在数组中的位置(0-9),我该怎么做?

int smallest = array[0];

for (counter = 0; counter < 10; counter++) {
    if (smallest > array[counter]) {
       smallest = array[counter];
    }
}

printf("The smallest value stored within the array is %d", smallest);

最佳答案

您只需要另一个变量(初始化为“0”),每次 if 条件为真时,在其中存储“counter”的值,如下所示:

int smallest = array[0];

int position = 0;

for (counter = 0; counter < 10; counter++) {
     if (smallest > array[counter]) {
       smallest = array[counter];
       position = counter;
  }
}

printf("The smallest value stored within the array is %d and position = %d", smallest, position);

关于c - 如何在C中打印数组中值的位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40822959/

相关文章:

c - 为什么 PostgreSQL 数组访问在 C 中比在 PL/pgSQL 中快得多?

PHP,使用公共(public)键合并数组

javascript - TypeScript - 自定义类元素的 Array.map

c - 使用虚拟 shell 时,如何检测用户是否在程序和参数后输入 '&'?

javascript - 如果数组是稀疏的,为什么 array.indexOf(undefined) 不起作用

c - atomic_cas_64() 在 Solaris on Sparc 上的内部实现?

C 编程 ... 为什么 "return"语句在这段代码中只给出一个值?

c - 如何在递增后使用递归进行递减计数

c - FprintF 从链接列表到文件

javascript - 按数组值的 Angular 自定义过滤器