Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

c++ - Find largest and smallest number in an array

Consider:

#include <iostream> // Include header file

using namespace std;

int main () //start of main function
{

    int values[20]; // Declares 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 the user for a value and stores it
    {
        cout << "Enter value " << i << ": ";
        cin >> values[i];
    }

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

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

    cout << "The biggest number is " << big << endl; // Prints outs the biggest number
    cout << "The smallest number is " << small << endl; // Prints out the smallest number
}

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 separately. Any suggestions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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) << "
";
std::cout << "max element " << *(minmax.second) << "
";

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...