C++查找0-9随机整数数组最大元素的最大索引
现有代码问题排查
- findLargest函数破坏原数组:该函数直接用
arr[0]存储临时最大值,遍历过程中会覆盖原数组的第一个元素,导致后续largestIndex拿到的数组已经不是初始随机生成的数组,逻辑完全失真。 - largestIndex函数硬编码最大值:直接判断
arr[i] == 9,但随机数组的最大值不一定是9(比如全是0-7的元素),永远找不到正确索引。 - 输出语句逻辑错误:
"The index of the largest element is " + i是C语言风格的字符串指针偏移运算,不是字符串和整数拼接,会输出乱码甚至触发内存访问错误。 - 未满足“取最大元素最后一次出现索引”的需求:当前只要匹配到等于9的元素就输出,会输出所有匹配项的索引,而非最后一次的位置。
- srand调用位置不规范:将随机数种子初始化放在
initialize内部,若多次调用该函数,同一秒内会生成完全相同的随机数组,属于冗余且不规范写法。
修复方案
核心调整:
- 改写
findLargest为返回最大值的整型函数,用临时变量存储最大值,不修改原数组。 largestIndex直接接收最大值参数,遍历数组时每遇到等于最大值的元素就更新索引变量,遍历结束后得到的就是最后一次出现的索引。- 修正输出语句,拆分字符串和索引值到不同的
cout输出流中。 - 将
srand(time(0))移到main函数中,仅初始化一次随机数种子。
修复后完整代码
#include <iostream> #include <ctime> #include <time.h> using namespace std; void initialize(int arr[], int size); void print(int arr[], int size); int findLargest(int arr[], int size); void largestIndex(int arr[], int size, int largestVal); int main(){ const int SIZE = 10; int myList[SIZE]; // 随机数种子仅初始化一次 srand(time(0)); initialize(myList, SIZE); print(myList, SIZE); int maxVal = findLargest(myList, SIZE); cout << "The largest element in the array is " << maxVal << endl; largestIndex(myList, SIZE, maxVal); return 0; } void initialize(int arr[], int size){ for(int i = 0; i < size; i++){ arr[i] = rand() % 10; } } void print(int arr[], int size){ for(int j = 0; j < size; j++){ cout << arr[j] << endl; } } int findLargest(int arr[], int size){ // 用临时变量存储最大值,不修改原数组 int currentMax = arr[0]; for(int i = 1; i < size; i++){ if(currentMax < arr[i]){ currentMax = arr[i]; } } return currentMax; } void largestIndex(int arr[], int size, int largestVal){ int lastIndex = 0; // 遍历所有元素,每匹配到最大值就更新索引,最终保留的是最后一次出现的位置 for(int i = 0; i < size; i++){ if(arr[i] == largestVal){ lastIndex = i; } } cout << "The index of the largest element is " << lastIndex << endl; }
内容的提问来源于stack exchange,提问作者Cyrus
相关产品推荐
相关产品推荐

