找到一个数组的最大和最小数 [英] find largest and smallest number in an array

查看:120
本文介绍了找到一个数组的最大和最小数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <iostream> //include header file

using namespace std;

int main () //start of main fcn
{

    int values[ 20 ]; //delcares array and how many elements
    int small,big; //declares integer
    big=small=values[0]; //assigns element to be highest or lowest value


    for ( int i = 0; i < 20; i++ ) //counts to 20 and prompts user for value and stores it
    {
        cout << "Enter value " << i << ": ";
        cin >> values[i];
    }

    for (int i = 0; i < 20; i++) //works out bigggest number
    {
        if(values[i]>big) //compare biggest value with current element
        {
            big=values[i];
        }
    }

    for (int i = 0; i < 20; i++) //works out smallest number
    {
        if(values[i]<small) //compares smallest value with current element
        {
            small=values[i];
        }
    }

    cout << "The biggest number is " << big << endl; //prints outs biggest no
    cout << "The smallest number is " << small << endl; //prints out smalles no
}

这是我的code到目前为止,我遇到的问题是它打印出数组的最大数量。是与分配给最高值和最低值的第一个元素。它的工作原理,如果我做他们分开。有什么建议?

This is my code so far the problem I am having is with it printing out the biggest number of the array. Something to do with assigning the first element to the highest and lowest value. It works if I do them seperately. Any suggestions?

推荐答案

除非你真的必须实现自己的解决方案,你可以使用的的std :: minmax_element 。这将返回一对迭代器,一个最小的元素,一个是最大的。

Unless you really must implement your own solution, you can use std::minmax_element. This returns a pair of iterators, one to the smallest element and one to the largest.

#include <algorithm>

auto minmax = std::minmax_element(std::begin(values), std::end(values));

std::cout << "min element " << *(minmax.first) << "\n";
std::cout << "max element " << *(minmax.second) << "\n";

这篇关于找到一个数组的最大和最小数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆