简体   繁体   English

C++如何在n个元素的一维数组中找到最小值和最大值?

[英]C++ How to find min and max values in a one-dimensional array of n elements?

Write a program that asks a user to input an integer n.编写一个程序,要求用户输入一个整数 n。 The program should prompt the user to input n integers and store them in a one-dimensional array.程序应该提示用户输入 n 个整数并将它们存储在一个一维数组中。 Then the program should output the minimum and maximum elements in the array.然后程序应该输出数组中的最小和最大元素。

int main()
{
    int n,a,b;
    cin>>n;
    int ma=0,mi=0;
    int num[n];
    cin>>num[0];
    for(int i=1;i<n;i++)
    {
        cin>>num[i];
        a=num[i];
        b=num[i-1];
        if(a>b)
            ma=a;
        if(a<b)
            mi=a;
    }

    cout<<mi<<endl;
    cout<<ma;
}

When given elements, it doesn't show the min and max values correctly.当给定元素时,它不会正确显示最小值和最大值。 Where is my mistake?我的错误在哪里?

You missed that the first value in your algo will never be set as a min or as a max value.您错过了算法中的第一个值永远不会设置为最小值或最大值。 Let's assume all the numbers are positive ones假设所有数字都是正数

int main()
{
    int n;
    cin>>n;
    int ma=0,mi=2147483647;
    int num[n];
    for(int i=0;i<n;i++)
        {
            cin>>num[i];
            if(num[i] > ma)
                ma = num[i];
            if(num[i] < mi)
                mi = num[i];
        }


    cout<<mi<<endl;
    cout<<ma;
}

I would try the following code:我会尝试以下代码:

std ::vector < int > v (n);
std ::copy_n (std ::istream_iterator < int, char > (cin), begin (v), n);
auto const r ((std ::minmax_element) (begin (v), end (v)));
return std ::cout << * r .first << '\n' << * r .second ? EXIT_SUCCESS: EXIT_FAILURE;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM