You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:C语言如何获取随机数组中最大最小值的对应索引

解决C语言数组中最大值、最小值及其索引的获取问题

你现在的问题核心是只保存了最值的数值,没记录它们对应的索引,只要加两个变量专门存索引就行,看下面的修改:

关键修改点:

  • 新增两个整型变量 largestIndex 和 smallestIndex,用来记录最值所在的索引位置
  • 初始化时,把这两个索引变量和最值变量一起设为数组第一个元素的位置(0)
  • 在遍历数组比较数值时,更新最值的同时,同步更新对应的索引

修改后的完整代码

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define SIZE 10
#define MIN 100
#define MAX 990

int main(void) {
  int index;
  float array[SIZE];
  float largestValue, smallestValue;
  // 新增两个变量存储最值的索引
  int largestIndex, smallestIndex;

  srand(time(NULL));
  
  for (index = 0; index < SIZE; index++) {
    array[index] = (rand() % (MAX - MIN + 1) + MIN) / 10.0;
    printf("Index [%i]: %.1f\n", index, array[index]);
  }

  // 初始化最值和对应的索引为数组第一个元素
  largestValue = array[0];
  largestIndex = 0;
  smallestValue = array[0];
  smallestIndex = 0;

  for (index = 0; index < SIZE; index++){
    if (array[index] > largestValue) {
      largestValue = array[index];
      largestIndex = index; // 更新最大值索引
    }
    if (array[index] < smallestValue) {
      smallestValue = array[index];
      smallestIndex = index; // 更新最小值索引
    }
  }

  // 正确输出最值和对应的索引
  printf("最小值: [%i] %.1f\n", smallestIndex, smallestValue);
  printf("最大值: [%i] %.1f\n", largestIndex, largestValue);

  return 0;
}

解释你之前的错误尝试:

  1. 用循环结束后的index输出:循环结束时index等于SIZE(也就是10),这已经超出数组的合法索引范围(0-9),所以是错的。
  2. 用array[smallestValue]:smallestValue是浮点数,数组下标必须是整数,这种写法会导致编译错误或者非法内存访问,完全不可行。

内容的提问来源于stack exchange,提问作者user18912852

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 11:01:04