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

时间:2016-11-26 20:45:46

标签: 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);

2 个答案:

答案 0 :(得分:1)

你只需要另一个变量(初始化为“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);

答案 1 :(得分:0)

你的意思是这样的!

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

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