【问题标题】:Finding the smallest number in an array查找数组中的最小数
【发布时间】:2019-02-13 17:03:12
【问题描述】:

我正在尝试在数组中创建随机数,然后在该数组中找到最小的数。如何修改我的代码以使其正常工作?

using namespace std; 

int one, two, three, four; 

int main(){

  srand (time(NULL));

  one = rand() % 6 + 1;

  two = rand() % 6 + 1;

  three = rand() % 6 + 1;

  four = rand() % 6 + 1;

  int myelement [4] = {four, three, two, one};

  cout << myelement, myelement[+4] << endl;

  cout << min_element(myelement, myelement[+4]);

  return 0; 

}

【问题讨论】:

    标签: c++ arrays random min


    【解决方案1】:

    std::min_element() 函数不会将取消引用的指针作为参数,而这正是您对 myelement[+4] 所做的事情。传入迭代器并返回一个迭代器:

    auto it = std::min_element(std::begin(myelement), std::end(myelement));
    std::cout << *it;
    

    确保包含 &lt;algorithm&gt; 标头。

    还有,这个:

     cout << myelement, myelement[+4] << endl;
    

    由于多种原因是错误的。

    这个:

    cout << myelement;
    

    不打印出第一个元素。当您的数组在函数中使用时,它会打印指针值。

    这个:

     cout << myelement[+4];
    

    不打印第四个元素值,但会导致未定义的行为,因为没有 myelement[+4] 这样的元素,只有 myelement[3]。

    【讨论】:

      【解决方案2】:

      您已经找到了最小的数字。您只是没有考虑到 min_element() 将 iterators 作为输入并返回一个 iterator 作为输出。您没有在第二个参数中传递有效的迭代器,您需要取消引用输出迭代器以获取实际数字。

      #include <iostream>
      #include <cstdlib>
      #include <ctime>
      #include <algorithm>
      using namespace std;
      
      int main(){
          srand (time(NULL));
          int one = rand() % 6 + 1;
          int two = rand() % 6 + 1;
          int three = rand() % 6 + 1;
          int four = rand() % 6 + 1;
          int myelement [4] = {four, three, two, one};
          cout << *min_element(myelement, myelement+4);
          return 0;
      }
      

      【讨论】:

      • 它是&lt;cstdlib&gt; 和&lt;ctime&gt;。 &lt;algorithm&gt; 仍然不见了。
      • 你真的很棒
      猜你喜欢
      • 2013-04-24
      • 2018-09-24
      • 1970-01-01
      • 1970-01-01
      • 2021-11-29
      • 2015-04-18
      • 1970-01-01
      • 2015-02-03
      相关资源
      最近更新 更多