【问题标题】:Get the maximum number from an integer array in C++从C ++中的整数数组中获取最大数
【发布时间】:2012-11-05 00:39:11
【问题描述】:

我的学校还有另一项任务是:

编写一个程序,从三个输入的数字中输出最大的数字

到目前为止,我已经这样做了:

#include <cstdlib>
#include <iostream>

using namespace std;

int main(int argc, char *argv[])
{
    int* numbers = new int[3];

    for(int i = 0; i < 3; i++) {
        cout << "Input number no. " << (i + 1);
        cin >> numbers[i];
        cout << endl;
    }


    system("PAUSE");
    return EXIT_SUCCESS;
}

C++ 中是否有一个辅助函数/方法可以在我的numbers 数组中找到最大的数字?

【问题讨论】:

  • 是的,有std::max_element:en.cppreference.com/w/cpp/algorithm/max_element 它需要迭代器作为参数(一个到数组的开头,一个到数组的末尾)。您可以将指针用作迭代器。
  • 您输入的密码错误。如果您不明白为什么,请确保您学习了如何在 C++ 中使用 iostream。作为一个测试,如果你调用echo "" | myprogram,你的程序必须能够存活。
  • @KerrekSB 谢谢你的建议 :)
  • 既然你知道会有三个数字,你可以直接使用int numbers[3],而不是使用new创建数组而忘记删除它。

标签: c++ arrays input max


【解决方案1】:

有一种算法可以在 容器 (std::max_element) 中找到最大元素,但这是不合适的。您的情况可以通过constant 内存消耗来解决,因此您不需要存储所有数字。在任何给定点,您只需要记住当前的最大值。

想象一下,您必须处理无数个数字。然后将它们全部存储起来是不可取的。

当然,max_element 算法在内部的作用与我刚才建议的相同,但它假定您已经拥有容器。如果你不这样做,那么只需即时更新最大值。 boost.accumulators 库可以做到这一点,但我相信你可以自己编写它——它应该只需要一两行代码。

【讨论】:

    【解决方案2】:

    在以下代码 sn-p 中,max 将包含列表中的最高数字:

    int i;
    int max=numbers[0];
    for(i=1;i<3;i++)
    {
       if(numbers[i]>max) max=numbers[i];
    }
    

    注意:您的数组看起来太小了 - 它的大小为 2,我很确定您想要 3 的大小。

    【讨论】:

      【解决方案3】:

      这里不需要数组。看看他们进来的数字:

      int largest = std::numeric_limits<int>::min();
      for (int i = 0; i < 3; ++i) {
          int value;
          std::cin >> value;
          if (largest < value)
              largest = value;
      }
      

      【讨论】:

        猜你喜欢
        • 2014-06-11
        • 1970-01-01
        • 2014-05-22
        • 1970-01-01
        • 2016-05-25
        • 2011-10-04
        • 2014-02-28
        • 1970-01-01
        • 2018-04-15
        相关资源
        最近更新 更多