【问题标题】:Finding the index of largest number [closed]查找最大数字的索引[关闭]
【发布时间】:2019-08-16 10:15:16
【问题描述】:

我想在 C 中找到给定数组中最大元素的索引。

我尝试了插入排序算法来确定数组中的最大值,然后我将最大值与我之前所有数组的元素进行了比较,但它不起作用。

void insertion_array(float array[], int n) //* insertion algorithm*//
{
    int i = 1, j;
    float x;

    for (; i < n; i++) {
        x = array[i];
        j = i - 1;

        while ((j >= 0) && (array[j] > x)) {

            array[j + 1] = array[j];
            j = j - 1;

        }
        array[j + 1] = x;
    }
}

uint8_t Largest_Number_Finder(float arr[], uint8_t n) {
    uint8_t index;
    insertion_array(arr, n);
    for (int i = 0; i < n; i++) {
        if (arr[i] > arr[n - 1]) {
            index = i;

        }
    }
    return index;
}

我希望采用最大数字索引,但算法总是给出最后一个元素的索引。我应该怎么做才能使它正确? 编辑=您作为重复导航的内容是找到最大的元素。我的目标是找到数组中最大元素的索引。

【问题讨论】:

  • 不需要排序。首先假设第一个元素(索引 0)是最大的。然后循环遍历所有元素,如果有大于当前最大元素的元素,保存其索引,继续循环。
  • 我明白了谢谢@Someprogrammerdude
  • 有一些修改它应该有助于@Renat
  • 除其他问题外,您的代码似乎永远不会为 index 分配值,因此可能会以未初始化的方式返回,即 UB

标签: c arrays sorting


【解决方案1】:

正如评论中提到的“一些程序员老兄”,如果您的目的只是找到最大值的索引,则不需要实现插入或任何其他算法来对数组进行排序。

您可能可以制作这样的功能。

int find_max_value(float array[], int length)
{
    // set the value of index 0 as the "current max value"
    float max_value = array[0];
    // the same goes for the index number
    int max_index = 0;

    // go through the array 
    for(int i = 1; i < length; i++)  
    {
        // if the next index's value is greater than the "current max value"
        // update the max_value and max_index
        if(array[i] > max_value)
        {
            max_value = array[i];
            max_index = i;
        }
    }
    return max_index;
}

并尝试使用任何输入值调用find_max_value() 函数,例如

int result = find_max_value(array1, 10);   // just an example supposing that you have declared an array called "array1" and its length is 10
printf("%d", result);    // see what the return value of the find_max_value() function would be

【讨论】:

  • 当我指向问题的标题时,我的目标是找到它的索引而不是值。确实,它适用于某些法规。
  • 对不起,我误解了原来的问题。我已经相应地更新了我的答案。
猜你喜欢
  • 2022-01-12
  • 2021-09-06
  • 2016-03-11
  • 2020-02-27
  • 1970-01-01
  • 1970-01-01
  • 2015-10-11
  • 1970-01-01
  • 2022-06-15
相关资源
最近更新 更多