找到包含N个元素的数组的最小值和最大值

Ker*_*rox 0 c++ arrays algorithm max min

我需要找到带N元素的数组的最小值和最大值.事实是我的程序正在运行,但是当我在网站上提交它时它只给出了我的32分数100,我不知道什么是错的.

#include <iostream>

using namespace std;

int main() {
    int N,min,max;
    cin >> N;
    min = N;
    max = N;

    int i,x;
    for (i = 1; i <= N; ++i) {
        cin >> x;

        if ( x < min ) {
            min = x;
        }
        if (x > max) {
            max = x;
        }
    }
    cout << min <<" "<< max;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

JeJ*_*eJo 5

你的逻辑在这里

min = N;
max = N;
Run Code Online (Sandbox Code Playgroud)

用它们初始化它们N是错误的.例如0,如果您的用户输入中包含最小数字,并且您N的数字大于此值0,则永远不会找到最小值.最大值也会发生同样的情况.

min使用最大可能值intmax最小可能值初始化,如下所示:

int min = std::numeric_limits<int>::max();
int max = std::numeric_limits<int>::min();
Run Code Online (Sandbox Code Playgroud)

建议 - 1

因为看起来你不想保存用户输入来查找mim和max,你可以使用std::minstd::max运行如下:

#include <iostream>
#include <limits>    //  std::numeric_limits<>
#include <algorithm> //  std::min, std::max

int main()
{
    // initialize like this
    int min = std::numeric_limits<int>::max();
    int max = std::numeric_limits<int>::min();
    int N;
    std::cin >> N;
    while (N--)
    {
        int x; std::cin >> x;
        min = std::min(x, min);  // use std::min
        max = std::max(x, max);  // use std::max
    }
    std::cout << min << " " << max;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

建议 - 2

如果要查找已存在数组的最小 - 最大值,可能需要考虑使用std :: minmax_element.

#include <algorithm>   //  std::minmax_element
#include <iostream>
#include <vector>

int main()
{
    int N; std::cin >> N;
    std::vector<int> v(N);
    for(auto& element: v) std::cin >> element;
    // do something.....

    // to find min-max of the array
    auto result = std::minmax_element(v.begin(), v.end());
    std::cout << "min element is: " << *result.first << '\n';
    std::cout << "max element is: " << *result.second << '\n';
}
Run Code Online (Sandbox Code Playgroud)

旁注:不练习std namespüace std;,为什么?看到这篇文章:为什么"使用命名空间std"被认为是不好的做法?