【问题标题】:why is my code not finding the index in my array?为什么我的代码在我的数组中找不到索引?
【发布时间】:2022-01-16 11:36:56
【问题描述】:

我已将我的代码放在下面。基本上,我找到数组中元素的最小编号,并且我还希望它找到最小元素的索引。它会找到元素数量相当少的索引,但由于某种原因,它有时似乎只是为索引返回随机数,我不知道为什么。

#include<iostream>
using namespace std;
    
int main()
{
    int min;
    int array[100];
    int size;
    int i;
    int index = 0;

    cin >> size;

    for (i = 0; i < size; i++)
    {
        cin >> array[i];
    }
    min = array[0];

    for (i = 0; i < size; i++)
    {
        
        if (min > array[i])
        {
            min = array[i];
            
        }
        index++;
    }
    cout << "The smallest number is " << min << " and is found at index " << index;
    return 0;
}

【问题讨论】:

  • 如果size大于100怎么办?
  • 你在第二个循环中无条件地增加index,所以到最后你总是有index == size。如果if 正文,您可能想要index = i inside 之类的东西。

标签: c++ arrays algorithm for-loop min


【解决方案1】:

您在 for 循环的每次迭代中增加变量 index

index++;

而变量min是多余的。

for 循环可以如下所示

for (i = 1; i < size; i++)
{
    if ( array[i] < array[index] )
    {
        index = i;
    }
}

cout << "The smallest number is " << array[index] << " and is found at index " << index;

注意有标准算法std::min_element() 执行相同的任务。

例如

#include <iterator>
#include <algorithm>

//...

auto min = std::min_element( array, array + size );

std::cout << "The smallest number is " << *min << " and is found at index " << std::distance( array, min ) << '\n';

【讨论】:

    【解决方案2】:

    您只需在循环外添加一个索引变量并将其设置为零。那么每次你的最大项目改变时,你的索引也会改变。

    #include<iostream>
    using namespace std;
        
    int main()
    {
        int min;
        int array[100];
        int size;
        int i;
        int index = 0;
    
        cin >> size;
    
        for (i = 0; i < size; i++)
        {
            cin >> array[i];
        }
        min = array[0];
        index =0
        for (i = 0; i < size; i++)
        {
            
            if (min > array[i])
            {
                min = array[i];
               index =i
                
            }
          i++;
        }
        cout << "The smallest number is " << min << " and is found at index " << index;
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-21
      • 2020-01-07
      • 2015-10-31
      相关资源
      最近更新 更多